给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置。
依次求数组的前缀和,同时执行如下操作:
假定当前位置是i,查找i之前位置的前缀和,是否存在j位置,使得,j位置的前缀和 等于 i位置的前缀和。
若有,则j 到 i 之间的区间数的和为0.
直到遍历完整个数组。
时间复杂度O(n),空间复杂度O(n).
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> subarraySum(vector<int> nums){
// write your code here
int sum = 0;
vector<int> ret;
unordered_map<int, int> map;
map[0] = -1;
for(int i=0; i<nums.size();i++)
{
sum += nums[i];
if(map.find(sum) != map.end())
{
ret.push_back(map[sum] +1);
ret.push_back(i);
return ret;
}
map[sum] = i;
}
return ret;
}
};
原文地址:http://blog.csdn.net/tommyzht/article/details/47401717