和为k的连续子数组
作者:互联网
方法一、暴力法
方法二、前缀和 + HashMap
求解和的方式往往能够分解成sum-k方式,查找此key是否在该dict中,count累加计数
# prefix sum nums = [1,1,1,1] k, count = 2, 0 dic = {0:1} # 和为key的前缀和有value个 prefix_sum = 0 for i in range(len(nums)): prefix_sum += nums[i] if prefix_sum - k in dic: count += dic[prefix_sum-k] if prefix_sum in dic: dic[prefix_sum] += 1 else: dic[prefix_sum] = 1 count
标签:count,key,nums,sum,dic,prefix,连续,数组 来源: https://www.cnblogs.com/demo-deng/p/16615128.html