问题描述:
给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置
注意事项
There is at least one subarray that it's sum equals to zero.
给出 [-3, 1, 2, -3,
4]
,返回[0, 2]
或者 [1,
3]
.
解题思路:
建立一个向量,储存符合要求的元素的起始位置和结束位置。从数组的第一个元素开始依次将元素加起来直到和为0跳出循环,如果相加的第一个元素为0则直接跳出,否则从该元素向后依次相加。如果没有符合要求的,就从第二个元素往后加,依次循环。
代码实现:
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> lz;
int a=nums.size();
int c;
for(int i=0;i<a;i++){
c=nums[i];
if(c==0){
lz.push_back(i);
lz.push_back(i);
break;
}
else for(int j=i+1;j<a;j++){
c+=nums[j];
if(c==0){
lz.push_back(i);
lz.push_back(j);
break;
}
}
if(c==0) break;
}
return lz;
}
};
解题感悟:
如果元素本身为0,就把该元素的下标放入向量,注意放两次。在外循环的最后判断加和是否为0,如果是0就跳出循环。若不判断,最终的向量中会出现几种不同的结果。