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

Subarray Sum

时间:2016-07-01 08:53:49      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

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.

Notice

There is at least one subarray that it‘s sum equals to zero.

Example

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

分析:

能够马上想到的答案是用两个for loop,找出从i 到 j 和为0的数。但是这里有一个更巧的方法。用一个array保存每个数和这个这个数之前的sum。

对于A = [-3, 1, 2, -3, 4], sum = [-3, -2, 0, -3, 1].

如果sum里面有0, 明显是index从 0 到当前数的和为 0。这是一种情况。还有一种情况是如果sum array里有两个相同的数,说明在这两个相同的数中间的数,它们的和也为0.

 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      * cnblogs.com/beiyeqingteng/
 7      */
 8     public ArrayList<Integer> subarraySum(int[] nums) {
 9         if (nums == null || nums.length < 1) return null;
10 
11         ArrayList<Integer> list = new ArrayList<Integer>();
12         int[] sum = new int[nums.length];
13         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
14 
15         for (int i = 0; i < nums.length; i++) {
16             if (i == 0) {
17                 sum[i] = nums[i];
18             } else {
19                 sum[i] = nums[i] + sum[i - 1];
20             }
21             
22             if (map.containsKey(sum[i])) {
23                 int index = map.get(sum[i]);
24                 list.add(index + 1);
25                 list.add(i);
26                 return list;
27             } else if (sum[i] == 0) {
28                 list.add(0);
29                 list.add(i);
30                 return list;
31             } else {
32                 map.put(sum[i], i);
33             }
34         }
35         return list;
36     }
37 }

转载请注明出处:cnblogs.com/beiyeqingteng/

 

 

Subarray Sum

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5631770.html

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