138. Subarray Sum【Lintcode,by java】

來源:互聯網
上載者:User

標籤: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了,那就跳出迴圈,返回結果。

My Code如下:

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】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.