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
相关推荐
洋不写bug7 小时前
排序(一)基础排序,插入|希尔|冒泡|直接选择排序详解
java·算法·排序算法·插入排序·冒泡排序·希尔排序·直接选择排序
牧羊人.3337 小时前
动手学深度学习 03 | 卷积神经网络实现手写数字识别
人工智能·深度学习·神经网络·算法·cnn
AgentMaster7 小时前
数据治理工具选型指南:一套可复用的四阶段决策框架
大数据·数据结构·人工智能·算法
liliangcsdn8 小时前
最终留出样本/样本外测试集-holdout解读
算法
爱敲代码的小黄8 小时前
机器学习入门:从数据、训练到业务决策
算法
数据知道8 小时前
哈希与密码存储——bcrypt、Argon2、盐值与彩虹表
网络·算法·安全·网络安全·密码学·哈希算法
haon11228 小时前
树模型在信贷风控怎么用——从决策树到 XGBoost
大数据·人工智能·算法·决策树·机器学习·数据挖掘
wordbaby8 小时前
BM25 是什么?手把手拆解搜索引擎的核心算法
人工智能·算法