Subarray Sum
原题链接:
Given an integer array, find a subarray where the sum of numbers is zero. Your code should return the index of the first number and the index of the last number.
样例
Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].
标签
SOLUTION 1:
我们有一个O(N)的解法。使用Map 来记录index, sum的值。当遇到两个index的sum相同时,表示从index1+1到index2是一个解。
注意:添加一个index = -1作为虚拟节点。这样我们才可以记录index1 = 0的解。
空间复杂度:O(N)
1 public class Solution { 2 /** 3 * @param nums: A list of integers 4 * @return: A list of integers includes the index of the first number 5 * and the index of the last number 6 */ 7 public ArrayListsubarraySum(int[] nums) { 8 // write your code here 9 10 int len = nums.length;11 12 ArrayList ret = new ArrayList ();13 14 HashMap map = new HashMap ();15 16 // We set the index -1 sum to be 0 to let us more convient to count.17 map.put(0, -1);18 19 int sum = 0;20 for (int i = 0; i < len; i++) {21 sum += nums[i];22 23 if (map.containsKey(sum)) {24 // For example: 25 // -3 1 2 -3 426 // SUM: 0 -3 -2 0 -3 127 // then we got the solution is : 0 - 228 ret.add(map.get(sum) + 1);29 ret.add(i);30 return ret;31 }32 33 // Store the key:value of sum:index.34 map.put(sum, i);35 }36 37 return ret;38 }39 }
GITHUB: