子数组之和
问题描述:
给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置。
样例
给出 [-3, 1, 2, -3, 4],返回[0, 2] 或者 [1, 3].
解题思路:
我的想法是数组的第一个值开始往后加,,每加一个值,把sum存一下,若能得到两个值相同的sum,则找到了一个和为0的子数组,子数组的范围就是第一个sum位置的后一位与第二个sum的位置。
代码实现:
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
if(nums.size()==0) return {};
map< int,vector<int> >hash;
hash[0].push_back(-1);
int sum=0;
int i;
for(i=0;i<nums.size();i++){
sum+=nums[i];
if(hash[sum].size()==1){
return {hash[sum][0]+1,i};
}
else hash[sum].push_back(i);
}
return {};
}
};
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
if(nums.size()==0) return {};
map< int,vector<int> >hash;
hash[0].push_back(-1);
int sum=0;
int i;
for(i=0;i<nums.size();i++){
sum+=nums[i];
if(hash[sum].size()==1){
return {hash[sum][0]+1,i};
}
else hash[sum].push_back(i);
}
return {};
}
};
A题感悟:
思路虽然有,但是代码不好写,我自己用map容器写的代码只能通过38%的数据,一直改不过来,后来还尝试用了list,结果在codeblock中编译没问题,在lintcode上提交竟然编译不过,只好在百度了一下大神们的代码,我看着这个和我的想法差不多,就借鉴了一下,但是有两三行代码没明白为什么要这样写。