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.

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

分析:

结尾的元素要带个数字看看才知道是i还是i + 1

解法:

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> res = new ArrayList<Integer>();
        if (nums.length == 0) {
            return res;
        }
        HashMap<Integer, Integer> subarraySum = new HashMap<Integer, Integer>();
        subarraySum.put(0, -1);

        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            if (subarraySum.containsKey(sum) ) {
                res.add(subarraySum.get(sum) + 1);
                res.add(i);
                break;
            }
            subarraySum.put(sum, i);
        }

        return res;
    }
}

results matching ""

    No results matching ""