138. 子数组之和
给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置
样例
样例 1:
输入: [-3, 1, 2, -3, 4]
输出: [0,2] 或 [1,3]
样例解释: 返回任意一段和为0的区间即可。
样例 2:
输入: [-3, 1, -4, 2, -3, 4]
输出: [1,5]
注意事项
至少有一个子数组的和为 0
public class Solution {
/**
* @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 List<Integer> subarraySum(int[] nums) {
// write your code here
ArrayList<Integer> ret= new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
int sum=0;
for (int j = i; j < nums.length; j++) {
sum=sum+nums[j];
if (sum==0){
ret.add(i);
ret.add(j);
return ret;
}
}
}
return ret;
}
}