publicclassSolution { /** * @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 */publicArrayList<Integer> subarraySum(int[] nums) {ArrayList<Integer> result =newArrayList<Integer>();HashMap<Integer,Integer> map =newHashMap<Integer,Integer>();int len =nums.length;int sum =0;map.put(0,-1);for (int i =0; i < len; i++) { sum += nums[i];if (map.containsKey(sum)) {result.add(map.get(sum) +1);result.add(i);return result; }map.put(sum, i); }return result; }}
易错点
是从 i + 1 到 j
result.add(map.get(sum) +1);
第一个 index = -1,这样 i + 1 这个 index 才能取到 0
map.put(0,-1);
找到一个值立马return
if (map.containsKey(sum)) {result.add(map.get(sum) +1);result.add(i);return result;}