LeetCode热题100-和为 K 的子数组

张开发
2026/4/19 23:51:59 15 分钟阅读

分享文章

LeetCode热题100-和为 K 的子数组
给你一个整数数组nums和一个整数k请你统计并返回该数组中和为k的子数组的个数。子数组是数组中元素的连续非空序列。题目要求连续非空序列所以这里不能排序可以使用前缀和 哈希表从前缀和中查找cur_profix - k出现的次数直接相加最终得到个数。from collections import defaultdict class Solution: def subarraySum(self, nums: List[int], k: int) - int: if not nums: return 0 profix_dic defaultdict(int) profix_dic[0] 1 cur_profix 0 res 0 for num in nums: cur_profix num if cur_profix - k in profix_dic: res profix_dic[cur_profix - k] profix_dic[cur_profix] 1 return res

更多文章