# Your NumArray object will be instantiated and called as such: # obj = NumArray(nums) # param_1 = obj.sumRange(left,right)
560、和为K的子数组
思路:
构造s数组,然后将每个位置的值设置为对应的前缀和,连续的子数组的和就为s[j]-s[i]
myhash存储的是对应元素出现的次数,例如和为1的子数组出现的次数
两次遍历:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: defsubarraySum(self, nums: List[int], k: int) -> int: myhash = defaultdict(int) s = [0] * (len(nums) + 1) for index, num inenumerate(nums): s[index + 1] = s[index] + num # print(s) # 连续的子数组之和为K s[j]-s[i]=k # s[j]-s[i]=连续子数组和=k res = 0 # 需要注意特殊情况 nums=[1],k=1的情况,如果s不设置s[0]就会出现结果为0的情况 for ss in s: res += myhash[ss - k] myhash[ss] += 1 return res
一次遍历:
一边计算前缀和,一边遍历前缀和
1 2 3 4 5 6 7 8 9 10
classSolution: defsubarraySum(self, nums: List[int], k: int) -> int: myhash = defaultdict(int) res = s = 0 myhash[0] = 1 for num in nums: s += num res += myhash[s - k] myhash[s] += 1 return res
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: defsubarraySum(self, nums: List[int], k: int) -> int: s = [0] * (len(nums) + 1) for index, num inenumerate(nums): s[index + 1] = s[index] + num # print(s) # [0,1,0,0] # 看差值是否在哈希表中 记录其出现的次数 res = 0 myhash = defaultdict(int) for ss in s: if ss - k in myhash: res += myhash[ss - k] myhash[ss] += 1