題目
給定一個整數(shù)數(shù)組,找到和為零的子數(shù)組。你的代碼應(yīng)該返回滿足要求的子數(shù)組的起始位置和結(jié)束位置
樣例
給出 [-3, 1, 2, -3, 4],返回[0, 2]或者 [1, 3]
分析
這里用了一個技巧:將數(shù)組從第一位依次相加,記錄每次的結(jié)果,如果map里面沒有,就加入map里,如果有,就證明前面肯定有為0的子數(shù)組,才會出現(xiàn)一樣的和。
代碼
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 ArrayList<Integer> subarraySum(int[] nums) {
// write your code here
int len = nums.length;
ArrayList<Integer> ans = new ArrayList<Integer>();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(0, -1);
int sum = 0;
for (int i = 0; i < len; i++) {
sum += nums[i];
if (map.containsKey(sum)) {
ans.add(map.get(sum) + 1);
ans.add(i);
return ans;
}
map.put(sum, i);
}
return ans;
}
}
.