枚举法,很容易想到↓
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
# nums_len 数组长度
nums_len=len(nums)
answer_count=0
n_sum=0
# 滑动指针(right_pointer&left_pointer)
for left_pointer in range(nums_len):
for right_pointer in range(left_pointer,nums_len):
n_sum+=nums[right_pointer]
if n_sum==k:
answer_count+=1
continue
n_sum=0
return answer_count
但是又超时了……
为什么超时了?解释如下↓
核心思想:前缀和+哈希表优化
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
# nums_len 数组长度
nums_len=len(nums)
answer_count=0
# 建立哈希表,以前缀和为键,出现的次数为值
Hash=dict()
# 必须将Hash[0]=1初始化,否则无法判断start=0的子数组是否满足条件
Hash[0]=1
pre=0
for i in range(nums_len):
pre+=nums[i]
# 由于i>j,必须最后更新Hash表
if pre-k in Hash:
answer_count+=Hash[pre-k]
else:
pass
#将pre[i]的值加入Hash表
Hash[pre]=Hash[pre]+1 if pre in Hash else 1
return answer_count
哈希表(hash table),也叫作散列表,这种数据结构提供了键(key)和值(value)的映射关系。只要给出一个key,就可以高效查找到它所匹配的value,时间复杂度接近于O(1)。
哈希函数就是将key和value值对应起来的函数。在不同语言中,哈希函数的实现方式是不一样的,在python语言中,哈希表对应的集合叫做字典(dict)。