Given An Array Of Integers Nums And An Integer K, Return The Total Number Of Continuous Subarrays Whose Sum Equals To K
def subarraySum(self, nums: List[int], k: int) -> int: count = 0 target = k self.cal(nums,target,count,k) return count def cal(nums,target, count,k): if targ
Solution 1:
You could try to use the prefix
idea and defaultdict()
to solve this Subarray Sum problem more elegantly and efficiently. It's depending on the prefix
sum idea, the code is easy to follow, you could try to run it with different data. In the dc[v]
we store all prefix sum, the num. of prev. prefix sum with value v. Then it loops and the array to see if new num. w
coming has value that satisfies w-v equal k
then we got a new count(pair).
from collections import defaultdict
class Answer :
def subarraySum(self, nums: List[int], k: int) -> int:
dc = defaultdict(int)
sum_ = 0
dc[0] = 1
result = 0
for n in nums:
sum_ += n
if sum_ - k in dc:
result += dc[sum_ - k]
dc[sum_] += 1
return result
Post a Comment for "Given An Array Of Integers Nums And An Integer K, Return The Total Number Of Continuous Subarrays Whose Sum Equals To K"