LeetCode 560. Subarray Sum Equals K(java)

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]

解法:这道题是maximum size subarray equals k的变形,区别在于这里是统计subarray的个数,思路还是类似的,用hashmap来做,用sum标记到i位置的当前和,然后通过hashmap找所需值,用value来存此和的个数。代码如下:
    public int subarraySum(int[] nums, int k) {
        if (nums.length == 0) return 0;
        HashMap map = new HashMap<>();
        map.put(0, 1);
        int sum = 0, result = 0;
        for (int i : nums) {
            sum += i;
            if (map.containsKey(sum - k)) {
                result += map.get(sum - k);
            }
            if (map.containsKey(sum)) {
                map.put(sum, map.get(sum) + 1);
            } else {
                map.put(sum, 1);
            }
        }
        return result;
    }

你可能感兴趣的:(计算机算法,java,leetcode)