[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.

Example

Given [-3, 1, 1, -3, 5], return [0, 2], [1, 3], [1, 1], [2, 2] or [0, 4]

Challenge

O(nlogn) time

http://www.lintcode.com/en/problem/subarray-sum-closest/

题目的意思是在一个数组中找一段连续的区间,使得这段区间的和的绝对值最小。做法就是利用前缀和,先用一个数组acc[i]来保存从nums[0]到nums[i]的和,同时还要记录下标,所以这里我用pair<int, int>来保存。那么,我们想要得到nums[i]到nums[j]的和,只要用acc[j] - acc[i-1]就可以了。但是这里有一点要注意要加一个辅助的节点,那就是[0, -1],这样就可以确保可以找到以nums[0]开始的区间了。剩下的工作就是对acc数组排序,找到排序后相邻的差的绝对值最小的那一对节点。

 1 class Solution {
 2 public:
 3     /**
 4      * @param nums: A list of integers
 5      * @return: A list of integers includes the index of the first number 
 6      *          and the index of the last number
 7      */
 8     vector<int> subarraySumClosest(vector<int> nums){
 9         // write your code here
10         vector<pair<int, int> > acc;
11         acc.push_back(make_pair(0, -1));
12         int sum = 0;
13         for (int i = 0; i < nums.size(); ++i) {
14             sum += nums[i];
15             acc.push_back(make_pair(sum, i));
16         }
17         sort(acc.begin(), acc.end());
18         int min_abs = INT_MAX, a, b, tmp;
19         for (int i = 1; i < acc.size(); ++i) {
20             tmp = abs(acc[i].first - acc[i-1].first);
21             if (min_abs >= tmp) {
22                 min_abs = tmp;
23                 a = acc[i-1].second;
24                 b = acc[i].second;
25             }
26         }
27         vector<int> res;
28         res.push_back(min(a, b) + 1);
29         res.push_back(max(a, b));
30         return res;
31     }
32 };

 

posted @ 2015-05-14 21:23  Eason Liu  阅读(1106)  评论(0编辑  收藏  举报