Using a hashmap to save the sum and index pair, initialize the map to <0, -1>
sum the integers in the array, if we meet a sum that exits in the map, means we found a subarray that sums to 0,
return the beginning and ending indices.
public class Solution {
public ArrayList<Integer> subarraySum(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
ArrayList<Integer> ret = new ArrayList<>();
map.put(0, -1);
int sum = 0;
for (int i=0; i<nums.length; i++) {
sum += nums[i];
if (map.containsKey(sum)) {
ret.add(map.get(sum)+1);
ret.add(i);
break;
}
map.put(sum, i);
}
return ret;
}
}