[LeetCode] 560. Subarray Sum Equals K(和为 K 的子数组)

Description

Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k.
给定一个整数数组 nums 和一个整数 k,返回和为 k 的子数组的个数

Examples

Example 1

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

Example 2

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

Constraints

  • 1 <= nums.length <= 2 * 104
  • -1000 <= nums[i] <= 1000
  • -1e7 <= k <= 1e7

Hints

  1. Will Brute force work here? Try to optimize it.
    暴力搜索管用吗?尝试优化它。

  2. Can we optimize it by using some extra space?
    我们能否通过使用一些额外空间优化它?

  3. What about storing sum frequencies in a hash table? Will it be useful?
    把和的频率存储成哈希表怎么样?管用吗?

  4. sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1. Can we use this property to optimize it.
    sum(i, j) = sum(0, j) - sum(0, i),其中 sum(i, j) 表示数组从下标 i 到下标 j - 1 之间所有元素的和。我们能否借此优化算法?

Solution

按照提示所言,采用前缀和+哈希表的方式遍历数组,首先累加前缀和,如果前缀和 - k 在哈希表里存在了,则计入最后的结果,最后更新前缀和出现的频率,代码如下:

class Solution {
    fun subarraySum(nums: IntArray, k: Int): Int {
        val sumFreq = hashMapOf(0 to 1)
        var prefix = 0
        var result = 0
        for (num in nums) {
            prefix += num
            if (sumFreq.containsKey(prefix - k)) {
                result += sumFreq.getValue(prefix - k)
            }
            sumFreq[prefix] = sumFreq.getOrDefault(prefix, 0) + 1
        }
        return result
    }
}
原文地址:https://www.cnblogs.com/zhongju/p/14051924.html