[LintCode] Subarray Sum Closest
2015-05-14 21:23
369 查看
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数组排序,找到排序后相邻的差的绝对值最小的那一对节点。
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数组排序,找到排序后相邻的差的绝对值最小的那一对节点。
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 vector<pair<int, int> > acc; acc.push_back(make_pair(0, -1)); int sum = 0; for (int i = 0; i < nums.size(); ++i) { sum += nums[i]; acc.push_back(make_pair(sum, i)); } sort(acc.begin(), acc.end()); int min_abs = INT_MAX, a, b, tmp; for (int i = 1; i < acc.size(); ++i) { tmp = abs(acc[i].first - acc[i-1].first); if (min_abs >= tmp) { min_abs = tmp; a = acc[i-1].second; b = acc[i].second; } } vector<int> res; res.push_back(min(a, b) + 1); res.push_back(max(a, b)); return res; } };
相关文章推荐
- **[Lintcode]Subarray Sum Closest最接近零的子数组和
- [LintCode]Subarray Sum Closest
- LintCode-Subarray Sum Closest
- LintCode 139. Subarray Sum Closest
- lintcode-medium-Subarray Sum Closest
- LintCode : 最接近零的子数组和 Subarray Sum Closest
- LintCode Subarray Sum Closest
- [刷题]Subarray Sum Closest
- lintcode 中等题:continuous subarray sum 连续子数组之和
- [LintCode] Continuous Subarray Sum 连续子数组之和
- lintcode:Subarray Sum Closest
- [LintCode] Minimum Size Subarray Sum 最小子数组和的大小
- lintcode: Subarray Sum Closest
- lintcode-Continuous Subarray Sum
- [Lintcode]Minimum Size Subarray Sum 和大于S的最小子数组
- #139 Subarray Sum Closest
- [Lintcode] Continuous Subarray Sum
- [LintCode 406] Minimum Size Subarray Sum(Python)
- 139. Subarray Sum Closest
- [LintCode] Continuous Subarray Sum