LintCode Subarray Sum Closest

本文介绍了如何在一个整数数组中找到一个子数组,使得其和最接近零,并提供了O(nlogn)时间复杂度的解决方案。

Given an integer array, find a subarray with sum closest to zero. Return the indexes of the first number and last number.
Have you met this question in a real interview? Yes
Example
Given [-3, 1, 1, -3, 5], return [0, 2], [1, 3], [1, 1], [2, 2] or [0, 4]
Challenge
O(nlogn) time

这个和前面一个subarray sum的题目有些类似,也是先求出累计和,然后再对他们排序,相近的累计和总是相邻的,于是可以得到最靠近的0的subarray sum

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return: A list of integers includes the index of the first number 
     *          and the index of the last number
     */
    vector<int> subarraySumClosest(vector<int> nums){
        // write your code here
        int len = nums.size();
        vector<int> res;
        vector<pair<int, int>> sums;
        int sum = 0;
        for (int i = 0; i < len; i++) {
            sum += nums[i];
            sums.push_back({sum, i});
            if (sum == 0) {
                res = {0, i};
                return res;
            }
        }
        
        sort(sums.begin(), sums.end());
        
        int diff = abs(sums[0].first);
        res = {0, 0};
        
        for (int i = 1; i < len; i++) {
            auto& prev = sums[i - 1];
            auto& curr = sums[i];
            int cdiff = abs(prev.first - curr.first);
            if (cdiff < diff) {
                diff = cdiff;
                if (prev.second < curr.second) {        
                    res = {prev.second + 1, curr.second};
                } else {
                    res = {curr.second + 1, prev.second};
                }
            }
        }
        
        return res;
    }
};

转载于:https://www.cnblogs.com/lailailai/p/4803754.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值