Subarray Sum
Original title Link: http://lintcode.com/zh-cn/problem/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 last number of the index.
Sample Example
Given [ -3, 1, 2, -3, 4], return [0, 2] or [1, 3].
label Expand
Solution 1:
We have an O (N) solution. Use map to record the value of index, sum. When the sum of two index is encountered at the same time, the representation from index1+1 to Index2 is a solution.
Note: Add an index =-1 as the virtual node. So that we can record the solution of index1 = 0.
Space complexity: O (N)
1 Public classSolution {2 /**3 * @paramnums:a List of integers4 * @return: A list of integers includes the index of the first number5 * The index of the last number6 */7 PublicArraylist<integer> Subarraysum (int[] nums) {8 //Write your code here9 Ten intLen =nums.length; One Aarraylist<integer> ret =NewArraylist<integer>(); - -Hashmap<integer, integer> map =NewHashmap<integer, integer>(); the - //We Set the index-1 sum to being 0 to let us more convient to count. -Map.put (0,-1); - + intsum = 0; - for(inti = 0; i < Len; i++) { +Sum + =Nums[i]; A at if(Map.containskey (sum)) { - //For Example: - //-3 1 2-3 4 - //sum:0 -3-2 0-3 1 - //Then we got the solution is:0-2 -Ret.add (Map.get (sum) + 1); in Ret.add (i); - returnret; to } + - //Store the Key:value of Sum:index. the map.put (sum, i); * } $ Panax Notoginseng returnret; - } the}
View Code
GITHUB:
Https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/lintcode/array/SubarraySum.java
Lintcode:subarray Sum Problem Solving report