LintCode Subarray Sum Closest

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;
    }
};


posted @ 2015-09-12 22:29  卖程序的小歪  阅读(117)  评论(0编辑  收藏  举报