当前位置:网站首页>leetcode-560:和为 K 的子数组
leetcode-560:和为 K 的子数组
2022-07-07 08:18:00 【菊头蝙蝠】
leetcode-560:和为 K 的子数组
题目
给你一个整数数组 nums 和一个整数 k ,请你统计并返回 该数组中和为 k 的子数组的个数 。
示例 1:
输入:nums = [1,1,1], k = 2
输出:2
示例 2:
输入:nums = [1,2,3], k = 3
输出:2
解题
方法一:前缀和(超时)
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int n=nums.size();
vector<int> preSums(n+1);
for(int i=0;i<nums.size();i++){
preSums[i+1]=preSums[i]+nums[i];
}
int count=0;
for(int i=1;i<=n;i++){
for(int j=0;j<i;j++){
if(preSums[i]-preSums[j]==k){
count++;
}
}
}
return count;
}
};
方法二:前缀和+哈希表
红色部分就是我们要求的和为k的子数组
如果当前遍历到的前缀和是presum,那么只要知道presum-k的个数就行了,对最后结果加上presum-k的个数
通过map去维护一个前缀和 的个数
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int,int> map;
map[0]=1;//前缀和为0的个数为1
int preSum=0;
int count=0;
for(int num:nums){
preSum+=num;
if(map.count(preSum-k)){
//加上前缀和为preSum-k的个数
count+=map[preSum-k];
}
map[preSum]++;
}
return count;
}
};
边栏推荐
- 【剑指Offer】42. 栈的压入、弹出序列
- ArcGIS operation: converting DWG data to SHP data
- The request object parses the request body and request header parameters
- 每周推荐短视频:L2级有哪些我们日常中经常会用到的功能?
- 关于hzero-resource报错(groovy.lang.MissingPropertyException: No such property: weight for class)
- ORM model -- creation and query of data records
- Postman interface test VI
- 【HigherHRNet】 HigherHRNet 详解之 HigherHRNet的热图回归代码
- 基于HPC场景的集群任务调度系统LSF/SGE/Slurm/PBS
- STM32产品介绍
猜你喜欢

求方程ax^2+bx+c=0的根(C语言)

AHB bus in stm32_ Apb2 bus_ Apb1 bus what are these

SolidWorks工程图中添加中心线和中心符号线的办法

ISP、IAP、ICP、JTAG、SWD的编程特点

Google colab loads Google drive (Google drive is used in Google colab)

每周推荐短视频:L2级有哪些我们日常中经常会用到的功能?

Appx代碼簽名指南

HAL库配置通用定时器TIM触发ADC采样,然后DMA搬运到内存空间。

Yarn的基础介绍以及job的提交流程

Leetcode exercise - 113 Path sum II
随机推荐
php \n 换行无法输出
HDU-2196 树形DP学习笔记
串口通讯继电器-modbus通信上位机调试软件工具项目开发案例
Can I open a stock trading account online? Is it safe
2022.7.4DAY596
STM32 ADC and DMA
2022.7.6DAY598
Postman interface test IV
Remote meter reading, switching on and off operation command
How to cancel automatic saving of changes in sqlyog database
When there are pointer variable members in the custom type, the return value and parameters of the assignment operator overload must be reference types
Multisim--软件相关使用技巧
P1031 [NOIP2002 提高组] 均分纸牌
Postman interface test VII
JMeter about setting thread group and time
[email protected] can help us get the log object quickly
[learning notes - Li Hongyi] Gan (generation of confrontation network) full series (I)
求最大公约数与最小公倍数(C语言)
根据设备信息进行页面跳转至移动端页面或者PC端页面
mysql插入数据创建触发器填充uuid字段值