2016年6月20日星期一

[LintCode] #138 Subarray Sum

http://www.lintcode.com/en/problem/subarray-sum/

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;
        }
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            
            if (sum == 0) {
                result.add(0);
                result.add(i);
                return result;
            }
            
            if (map.containsKey(sum)) {
                result.add(map.get(sum) + 1);//Attention
                result.add(i);
                return result;
            }
            
            map.put(sum, i);
        }
        return result;
    }
}



没有评论:

发表评论