1、问题描述
给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置。
样例
给出 [-3, 1, 2, -3, 4]
,返回[0, 2]
或者 [1, 3]
.
2、实现思路
从第一个开始,固定其值,若其为0,起始和终止位置都为当前位置下标,不为零,则从下一个开始,依次加和,至零则找到终止位置坐标。
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> b;
int a=nums.size();
int i,j,c;
for(i=0;i<a;i++)
{ c=nums[i];
if(c==0){ b.push_back(i);
b.push_back(i);
break; }
for(j=i+1;j<a;j++)
{ c=c+nums[j];
if(c==0) { b.push_back(i);
b.push_back(j);
break;}
}
if(c==0)break;
}
return b;
}
};
4、感想
创建一个空向量,将符合的起始和终止位置坐标加入,注意同一个起始位置找到一个终止位置即可,一个数组找到一对起始和终止坐标即可。