[lintcode easy]subarray sum

Subarray Sum

Example

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

Note

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

 

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
        ArrayList<Integer> list=new ArrayList<Integer>(0);
        if(nums.length==0) return list;
        int n=nums.length;

        for(int i=0;i<n;i++)
        {
            int sum=0;
             for(int j=i;j<n;j++)
            {
                sum += nums[j];
                
                if(sum==0)
                {
                    list.add(i);
                    list.add(j);
                    return list;
                }
                
            }
        }
        
        
        return list;
    }
}

 

posted on 2015-12-02 07:07  一心一念  阅读(135)  评论(0编辑  收藏  举报

导航