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

思路

最基础的subarray sum equals k,使用prefixSum + HashMap解决

复杂度

time O(n), space O(n)

代码

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

results matching ""

    No results matching ""