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

给你一个整数数组 nums 和一个整数 k ,请你统计并返回 该数组中和为 k的子数组的个数

子数组是数组中元素的连续非空序列。

题目要求连续非空序列,所以这里不能排序,可以使用前缀和 + 哈希表,从前缀和中查找cur_profix - k出现的次数直接相加,最终得到个数。

python 复制代码
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
相关推荐
海石1 小时前
1563分的简单题,可能就简单在能被暴力AC
算法·leetcode
海石2 小时前
1400分的dp汗流浃背之【交替子数组计数】
算法·leetcode
奋发向前wcx2 小时前
P2590 树的统计 题目解析
数据结构·算法·深度优先
imbackneverdie3 小时前
AI4S不止于分子药物:以MedPeer为代表的科研基建打开产业新增量
大数据·人工智能·算法·aigc·科研·学术·ai 4s
额鹅恶饿呃3 小时前
C语言中的数据结构和变量
c语言·数据结构·算法
运行时记录5 小时前
prompt-optimizer skill
算法
万法若空5 小时前
【数据结构-哈希表】哈希表原理
数据结构·算法·散列表
退休倒计时5 小时前
【每日一题】LeetCode 437. 路径总和 III TypeScript
算法·leetcode·typescript
学逆向的5 小时前
汇编——内存
开发语言·汇编·算法·网络安全
tachibana26 小时前
hot100 翻转二叉树(226)
java·数据结构·算法·leetcode