1.Description
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].
解讀
給定一個整數數組,和一個整數k,求有多少個連續子序列的和爲k。
2.Solution
解題思路:
最能想到的辦法就是遍歷了,存儲前n項的和,然後遞減回去,但是超時了
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if nums == []: return 0
sumlist, N = [nums[0]], 0
for i in range(1, len(nums)):
sumlist.append(sumlist[-1] + nums[i])
for i in range(len(sumlist)):
if sumlist[i] == k:
N = N + 1
for j in range(i):
if sumlist[i] - sumlist[j] == k:
N = N + 1
#print(N)
return N
那麼可以想到:通過記錄前n項和的次數,來快速得到解,什麼意思呢,
比如我們已經把前面n-1
項和的次數放入到了詞典中,比如{
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
count,cur,res={0:1},0,0
for num in nums:
cur=cur+num#計算前n項和
# (如果前n項和)cur-(需要求的和)k in (前n項和次數)詞典中,那麼get出來次數
res=res+count.get(cur-k,0)
count[cur]=count.get(cur,0)+1 #(如果前n項和)cur(的次數)在字典中加1
return res