描述
給定一個整數數組,找到和為零的子數組。你的代碼應該返回滿足要求的子數組的起始位置和結束位置
注意事項
There is at least one subarray that it's sum equals to zero.
樣例
給出 [-3, 1, 2, -3, 4],返回[0, 2] 或者 [1, 3].
知識點
所有子數組問題都需要求前綴和數組,數組的下標i代表原數組前i個數之和
代碼
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) {
ArrayList<Integer> ans = new ArrayList<Integer>();
// map的key是子數組之和,value是當前位置
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int sum = 0;
// 數組內沒有元素時,前綴和是0,若不加這行就會漏[0, 2]的解
map.put(0, -1);
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (map.containsKey(sum)) {
// prefix[i] 代表前 i 個數(下標 0 到 i-1)的和
// prefix[j+1] - prefix[i] 表示從 i+1 到 j 的子數組
// 對于 prefix[i] 要 +1, 因為子數組是從 i 的 下一個數開始的
ans.add(map.get(sum) + 1);
ans.add(i);
return ans;
}
map.put(sum, i);
}
// 數組不存在或數組內沒有元素時子數組和為0,不用寫異常
return ans;
}
}