[LintCode] Subarray Sum

462 查看

Problem

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.

Notice

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].

Note

HashMap<sum, index>记录数组nums每一位index之前的(包含当前位)所有元素之和。若有重复的sum出现,说明之前的sum对应的元素的下一位map.get(sum)+1到当前sum对应的第i个元素之间所有元素和为0,即为所求的子序列。

Solution

public class Solution {
    public ArrayList<Integer> subarraySum(int[] nums) {
        int n = nums.length;
        ArrayList<Integer> res = new ArrayList<Integer>();
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        map.put(0, -1);
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum += nums[i];
            if (map.containsKey(sum)) {
                res.add(map.get(sum)+1);
                res.add(i);
                return res;
            }
            else map.put(sum, i);
        }
        return res;
    }
}