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
相关推荐
Zachery Pole3 小时前
CCF-CSP备战NO.5链表(1)
数据结构·链表
圣光SG6 小时前
Java操作题练习(七)
java·开发语言·算法
Cx330_FCQ7 小时前
Tmux使用
服务器·git·算法
拳里剑气8 小时前
C++算法:多源BFS
c++·算法·宽度优先·多源bfs
ysa0510309 小时前
【板子】短序列dp(换成维护更小常数维度的dp)
c++·笔记·算法·板子
shwill1239 小时前
PID 算法(三)--- 增量 PID ↔ 单神经元 PID 等价映射
linux·算法
wabs66610 小时前
关于图论【卡码网110.字符串迁移的思考】
数据结构·算法·图论
hanlin0311 小时前
刷题笔记:力扣第242、349题(哈希表)
笔记·算法·leetcode
浮沉98711 小时前
二分查找算法例题(二)
算法
only-qi12 小时前
大模型Agent面试攻略:落地工程痛点、评估体系与Agentic RAG核心精讲
人工智能·算法·面试·职场和发展·langchain·rag