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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM