Thursday, March 23, 2017

Subarray Sum

第一次写,对于prefixsum的Index的问题想得特别混乱
需要借助手动跑case来确定各种+1还是 -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> result = new ArrayList<>();
        if (nums == null || nums.length == 0) return result;
        int[] prefixSum = new int[nums.length + 1];
        //Key - sum, Value - end index
        Map<Integer, Integer> hash = new HashMap<>();
        hash.put(0, 0);
        for (int index = 1; index < prefixSum.length; index++) {
            prefixSum[index] = prefixSum[index - 1] + nums[index - 1];
            if (hash.containsKey(prefixSum[index])) {
                result.add(hash.get(prefixSum[index]));
                result.add(index - 1);
                return result;
            }
            hash.put(prefixSum[index], index);
        }
        return result;
    }
}

No comments:

Post a Comment