[LeetCode] 560.Subarray Sum Equals K_Medium tag: Array, Subarray, prefix Sum

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 560.Subarray Sum Equals K_Medium tag: Array, Subarray, prefix Sum相关的知识,希望对你有一定的参考价值。

Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k.

 

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
  • -107 <= k <= 107

 

Ideas:

1. brute force     T: O(n ^2), S: O(1)

class Solution:
    def subarraySum(self, nums: List[int], target: int) -> int:
        n, count = len(nums), 0
        for i in range(n):
            for j in range(i, n):
                curSum = sum(nums[i: j + 1])
                if curSum == target:
                    count += 1
        return count

 

2. 参考Prefix Sum & Dictionary Time and Space O(n) for -- Find a number of continuous subarrays/submatrices/tree paths that sum to target     T: O(n), S: O(n)

class Solution:
    def subarraySum(self, nums: List[int], target: int) -> int:
        count, curSum, d = 0, 0, collections.Counter()
        for num in nums:
            curSum += num
            if curSum == target:
                count += 1
            count += d[curSum - target]
            d[curSum] += 1
        return count

 

以上是关于[LeetCode] 560.Subarray Sum Equals K_Medium tag: Array, Subarray, prefix Sum的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 560. Subarray Sum Equals K

[leetcode]Map-560. Subarray Sum Equals K

[LeetCode] 560. Subarray Sum Equals K_Medium

[LeetCode] 560.Subarray Sum Equals K_Medium tag: Array, Subarray, prefix Sum

LeetCode 560. Subarray Sum Equals K (子数组之和等于K)

leetcode560. Subarray Sum Equals K