当前位置:网站首页>LeetCode560. 和为K的子数组
LeetCode560. 和为K的子数组
2022-06-28 20:58:00 【Yuyy】
思路
首先想到的是暴力求解,双重循环得出所有连续子串,但是多半要超时。没想到其他办法。看了题解,学到了前缀和的概念,这里的子串和等于end的前缀和减去start的前缀和。在前缀和的基础上,结合了hash来优化,也就是两数之和那道题。
两个地方需要注意。一、需要的前缀和可能出现多次,那么每次都得算上。二、前缀和为0也是一种情况,并且是必要的,需要手动添加。例如目标为0。
题目
给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
示例 1 :
输入:nums = [1,1,1], k = 2
输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。说明 :
- 数组的长度为 [1, 20,000]。
- 数组中元素的范围是 [-1000, 1000] ,且整数 k 的范围是 [-1e7, 1e7]。
Related Topics
- 数组
- 哈希表
- 前缀和
- 1078
- 0
代码
public int subarraySum(int[] nums, int k) {
// key前缀和,value出现的次数
Map<Integer, Integer> qzh = new HashMap<>(nums.length);
// 子串长度为0(在母串最前面),前缀和为0,出现次数+1(原本为0)
qzh.put(0, 1);
// 前缀和
int sum = 0;
int res = 0;
for (int num : nums) {
sum += num;
// 找出需要的前缀和
final Integer target = qzh.get(sum - k);
if (target != null) {
res += target;
}
// 保存当前前缀和出现的次数
qzh.put(sum, qzh.getOrDefault(sum, 0) + 1);
}
return res;
}Post Views: 157
边栏推荐
猜你喜欢

Analysis of variance

pyechart绘制多条y轴折线图

I almost ran away

【筆記:模擬MOS集成電路】帶隙基准(基本原理+電流模+電壓模電路詳解)

Leetcode daily question - 515 Find the maximum value in each tree row

【笔记:模拟MOS集成电路】带隙基准(基本原理+电流模+电压模电路详解)

Learn Tai Chi maker mqtt Chapter 2 (VIII) esp8266 mqtt user password authentication

Query rewriting for opengauss kernel analysis

LeetCode每日一题——515. 在每个树行中找最大值

Racher add / delete node
随机推荐
Learn Tai Chi maker mqtt Chapter 2 (VIII) esp8266 mqtt user password authentication
国产数据库名录一览
Ref attribute, props configuration, mixin mixing, plug-in, scoped style
[Note: analog MOS integrated circuit] bandgap reference (basic principle + current mode + voltage mode circuit explanation)
Comparisonchain file name sort
Fix the simulator that cannot be selected by flutter once
题解 Pie(POJ3122)超详细易懂的二分入门
with torch. no_ Grad(): reason for using
软件watchdog和ANR触发memory dump讲解
No module named ‘PyEMD‘ ; Use plt figure()TypeError: ‘module‘ object is not callable
二叉树类题目 力扣
【读书会第13期】视频文件的封装格式
【学习笔记】聚类分析
Is it safe to open a dig money account? Is it reliable?
输入和输出字符型数据
openGauss内核分析之查询重写
实型数运算
Understanding of incomplete types
[Note: circuit intégré MOS analogique] référence de bande Gap (principe de base + mode courant + circuit en mode tension)
LeetCode每日一题——522. 最长特殊序列 II