Lintcode: Subarray Sum 解题报告

Subarray Sum

原题链接: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 index of the last number.

样例

Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].

标签 Expand

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 ArrayList<Integer> subarraySum(int[] nums) {
 8         // write your code here
 9         
10         int len = nums.length;
11         
12         ArrayList<Integer> ret = new ArrayList<Integer>();
13         
14         HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
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 4
26                 // SUM: 0 -3 -2  0 -3 1
27                 // then we got the solution is : 0 - 2
28                 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 }
View Code

 

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/lintcode/array/SubarraySum.java

posted on 2014-12-19 18:01  Yu's Garden  阅读(3695)  评论(1编辑  收藏  举报

导航