1. 程式人生 > 實用技巧 >[LeetCode] 560. Subarray Sum Equals K(和為 K 的子陣列)

[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 tok.
給定一個整數陣列 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
    }
}