1. 程式人生 > >138. Subarray Sum【Lintcode,by java】

138. Subarray Sum【Lintcode,by java】

urn 存儲 nta clu PE contain param 網上 amp

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】