当前位置:网站首页>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;
}
};
边栏推荐
- 【acwing】789. 数的范围(二分基础)
- Postman interface test II
- Kotlin实现微信界面切换(Fragment练习)
- IIC基本知识
- SQLyog数据库怎么取消自动保存更改
- Embedded background - chip
- Fiddler break point
- 大整数类实现阶乘
- Trajectory planning for multi-robot systems: Methods and applications 综述阅读笔记
- MCU is the most popular science (ten thousand words summary, worth collecting)
猜你喜欢

Some properties of leetcode139 Yang Hui triangle

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

一文讲解单片机、ARM、MUC、DSP、FPGA、嵌入式错综复杂的关系

P2788 数学1(math1)- 加减算式

0x0fa23729 (vcruntime140d.dll) (in classes and objects - encapsulation.Exe) exception thrown (resolved)

The request object parses the request body and request header parameters

Word自动生成目录的方法

1323:【例6.5】活动选择

Review of the losers in the postgraduate entrance examination

【acwing】789. 数的范围(二分基础)
随机推荐
字符串格式化
STM32基础知识—内存映射
fiddler-AutoResponder
Programming features of ISP, IAP, ICP, JTAG and SWD
学习记录——高精度加法和乘法
每周推荐短视频:L2级有哪些我们日常中经常会用到的功能?
CONDA creates virtual environment offline
嵌入式工程师如何提高工作效率
EasyExcel读取写入简单使用
ORM model -- associated fields, abstract model classes
2022.7.3DAY595
C#记录日志方法
LLVM之父Chris Lattner:為什麼我們要重建AI基礎設施軟件
table宽度比tbody宽度大4px
Fiddler simulates the interface test
求最大公约数与最小公倍数(C语言)
Postman interface test III
嵌入式背景知识-芯片
Adb 实用命令(网络包、日志、调优相关)
ORM -- query type, association query