版權(quán)聲明:本文為博主原創(chuàng)文章,未經(jīng)博主允許不得轉(zhuǎn)載。
難度:容易
要求:
給定一個(gè)整數(shù)數(shù)組,找到和為零的子數(shù)組。你的代碼應(yīng)該返回滿足要求的子數(shù)組的起始位置和結(jié)束位置
樣例
給出 [-3, 1, 2, -3, 4],返回[0, 2] 或者 [1, 3].
思路:
/**
* @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
*/
public ArrayList<Integer> subarraySum(int[] nums) {
int start = 0;
int end = 0;
int sum = 0;
labe:for(int i = 0; i < nums.length; i++){
sum = 0;
start = i;
for(int j = i; j < nums.length; j++){
sum += nums[j];
if(sum == 0){
end = j;
break labe;
}
}
}
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(start);
list.add(end);
return list;
}