码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode Subarray Sum

时间:2016-08-20 01:28:15      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

  技术分享

For this problem we need to learn a new trick that if your start sum up all elements in an array. When you start from a to b to sum up all elements, if the result is zero, and also the summation of all elements from index a to c ( c<=b ) is zero. Then, we need to think about sub array from index c+1 to index b is a sub array with summation of all elements to zero.

Notice: we need to formalize the summation of index =-1 to 0. Then if there is a sub array start from 0 has summation of 0, we will return the result.

 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         ArrayList<Integer> result = new ArrayList<Integer>();
10         HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();
11         //set index -1 sum to be 0 then when you meet an index with sum equals
12         //0 you can return otherwise there is never a 0 stored for the empty
13         //list
14         map.put(0,-1);
15         int sum = 0;
16         for (int i = 0; i < nums.length; i++ ) {
17             sum += nums[i];
18             if (map.containsKey(sum)) {
19                 result.add(map.get(sum) + 1);
20                 result.add(i);
21                 return result;
22             }
23             map.put(sum,i);
24         }
25         return result;
26     }
27 }

 

LintCode Subarray Sum

标签:

原文地址:http://www.cnblogs.com/ly91417/p/5789494.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!