描述
给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置
There is at least one subarray that it's sum equals to zero.
您在真实的面试中是否遇到过这个题?
是
样例
给出 [-3, 1, 2, -3, 4]
,返回[0, 2]
或者 [1, 3]
.
分析:
利用map<int>s存储从位置0开始到当前位置的sum和及其对应的位置
例1,给出 [-3, 1, 2, -3, 4],
s[-3]=0 ,s[-2]=1,s[0]=3
例2,给出 [10, 1, 2, -3, 4], s[10]=0 ,s[11]=1,s[13]=2,s[10]=3,说明中间的位置1,2,3和为零
真是一个神奇的解法!!!
代码如下:
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
vector<int> res;
unordered_map<int,int> m;
m[0]=-1;
int sum=0;
for(int i=0;i<nums.size();i++)
{
sum+=nums[i];
if(m.find(sum)!=m.end())
{
res.push_back(m[sum]+1);
res.push_back(i);
return res;
}
m[sum]=i;
}
return res;
}
};