lintcode-easy-Subarray Sum

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.

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

 

这道题的思路是这样的:

把数组中的数从头到尾逐个累加,并存到map中,sum为key,index为value

当出现了两个重复的累加和的时候,说明中间的一段子数组累加和为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
        ArrayList<Integer> result = new ArrayList<Integer>();
        
        if(nums == null || nums.length == 0)
            return result;
        
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        
        int sum = 0;
        int size = nums.length;
        
        for(int i = 0; i < size; i++){
            sum += nums[i];
            
            if(map.containsKey(sum)){
                result.add(map.get(sum) + 1);
                result.add(i);
                return result;
            }
            else{
                map.put(sum, i);
            }
        }
        
        result.add(0);
        result.add(nums.length - 1);
        return result;
    }
}

 

posted @ 2016-03-07 08:04  哥布林工程师  阅读(127)  评论(0)    收藏  举报