您的位置:首页 > 其它

lintcode: Subarray Sum Closest

2016-03-27 18:52 344 查看
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
另附参考链接:http://www.cnblogs.com/easonliu/p/4504495.html
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<int> retVtr;

if (nums.size() == 0)
return retVtr;

vector<pair<int, int>> auxVtr;
auxVtr.push_back(make_pair(0, -1));

int curSum = 0;
for (int i=0; i<nums.size(); i++)
{
curSum += nums[i];
auxVtr.push_back(make_pair(curSum, i));
}

sort(auxVtr.begin(), auxVtr.end());

int minDiff = INT_MAX;
int minA;
int minB;
for (int i=1; i<auxVtr.size(); i++)
{
if (auxVtr[i].first-auxVtr[i-1].first <= minDiff)
{
minDiff = auxVtr[i].first-auxVtr[i-1].first;
minA = auxVtr[i-1].second;
minB = auxVtr[i].second;
}
}

retVtr.push_back(min(minA, minB)+1);
retVtr.push_back(max(minA, minB));

return retVtr;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: