[LeetCode] 560. Subarray Sum Equals K

linspiration發表於2019-01-19

Problem

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:

Input:nums = [1,1,1], k = 2
Output: 2

Note:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

Solution

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

//1, 2, 3, 4, 5, 6          k = 5
//1, 3, 6, 10, 15, 21

//1, 1, 1, 2, 1, 2, 1       k = 3
//1, 2, 3, 5, 6, 8, 9

//1, 2, 0, -1, 0, 1         k = 2
//1, 3, 3,  2, 2, 3

相關文章