子数组之和
题目:
描述
给定一个整数数组,找到和为 00 的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置
至少有一个子数组的和为 0
样例
样例 1:
输入: [-3, 1, 2, -3, 4]
输出: [0,2] 或 [1,3]
样例解释: 返回任意一段和为0的区间即可。
样例 2:
输入: [-3, 1, -4, 2, -3, 4]
输出: [1,5]
解题思路:用HashMap记录相加和与对应最后一个元素的下标,当相加和已经出现过一次后再出现则说明此时出现了和为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
List<Integer> ans = new ArrayList();
int len = nums.length;
int sum = 0;
Map<Integer, Integer> map = new HashMap();
map.put(0, -1);
for(int i = 0; i < len; i++) {
sum += nums[i];
if(map.containsKey(sum)) {
ans.add(map.get(sum) + 1);
ans.add(i);
break;
}
map.put(sum, i);
}
return ans;
}
}