码迷,mamicode.com
首页 > 编程语言 > 详细

138. Subarray Sum【Lintcode,by java】

时间:2018-05-26 13:02:43      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:line   last   The   bsp   返回结果   XA   shm   red   turn   

Description

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.

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].

分析:题目给定一个数组,让你截取和为0的子数组,并返回该子数组的起点和终点的下标。先说一下我的思路,虽然时间复杂度达到平方级,但总的来说比较容易理解。外循环i表示子数组的起始下标,内循环表示以i为起点的子数组的终点下标。循环过程中,只要发现sum=0了,那就跳出循环,返回结果。

我的代码如下:

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: A list of integers includes the index of the first number and the index of the last number
     */
    public List<Integer> subarraySum(int[] nums) {
        // write your code here
        List<Integer>list=new ArrayList<Integer>();
        if(nums.length==1&&nums[0]==0){
            list.add(0);
            list.add(0);
        }
        for(int i=0;i<nums.length-1;i++){
            int sum=0;
            list.clear();
            list.add(i);
            for(int j=i;j<nums.length;j++){
                sum+=nums[j];
                if(sum==0){
                    list.add(j);
                    return list;
                }
            } 
        }
        return list;
    }
}

在网上看到另一种思路,线性级,感觉挺好的。利用哈希表,存储从起点到每个位置的和,如果哪两个位置的和相等,说明这两个数之间的子数组里的所有数的和为0。有点绕口,举个例子

有如下数组:

3,1,2,-1,2,2,1,-3,5   每个位置对应的和为:

3    4   6     5    7   9   10   7    13   发现有两个七,那么中间的那个子数组相当于没加,即【2,1,-3】和为0。下面贴上代码:

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: A list of integers includes the index of the first number
     *          and the index of the last number
     */
    public ArrayList<Integer> subarraySum(int[] nums) {
        // write your code here
       
        int len = nums.length;
       
        ArrayList<Integer> ans = new ArrayList<Integer>();
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
       
        map.put(0, -1);
       
        int sum = 0;
        for (int i = 0; i < len; i++) {
            sum += nums[i];
           
            if (map.containsKey(sum)) {
                ans.add(map.get(sum) + 1);
                ans.add(i);
                return ans;
            }
            
            map.put(sum, i);
        }
       
        return ans;
    }
}

 

138. Subarray Sum【Lintcode,by java】

标签:line   last   The   bsp   返回结果   XA   shm   red   turn   

原文地址:https://www.cnblogs.com/phdeblog/p/9092571.html

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