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
相关推荐
hhb_6188 小时前
AIRAGDebug:一键定位RAG链路异常
人工智能·python·算法
朝朝辞暮i8 小时前
C++ 第 6 课:switch —— 多状态选择
开发语言·c++·算法
苏打豆9 小时前
Pinocchio源码阅读——刚体运动物理量空间变换及求导
c++·线性代数·算法·矩阵·机器人
FluxArt9 小时前
GPT Image 2.5 中文提示词教程:Flux Art 可复用模板
前端·gpt·算法
思麟呀9 小时前
位运算:从一个整数到一个集合
c语言·数据结构·c++·算法
阜阳山君GEO10 小时前
豆包 SEED 新版本 GEO 优化:信源金字塔、打分体系与避坑落地指南
人工智能·算法
晓天衡宇•评测社区10 小时前
晓天衡宇亮相 2026 云栖大会:迈向更可信的高质量评测
人工智能·算法·机器学习
CQU_JIAKE10 小时前
9.12[a]
算法
CQU_JIAKE10 小时前
9.11【A】
算法
All for pursuit.11 小时前
【分治-3】347.前K个高频元素
数据结构·c++·算法·leetcode