当前位置:网站首页>Leetcode-560: subarray with sum K
Leetcode-560: subarray with sum K
2022-07-07 10:27:00 【Chrysanthemum headed bat】
leetcode-560: And for K Subarray
subject
Give you an array of integers nums And an integer k , Please count and return The array is k The number of subarrays of .
Example 1:
Input :nums = [1,1,1], k = 2
Output :2
Example 2:
Input :nums = [1,2,3], k = 3
Output :2
Problem solving
Method 1 : The prefix and ( Overtime )
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;
}
};
Method 2 : The prefix and + Hashtable
The red part is the sum we require k Subarray 
If the prefix sum currently traversed is presum, So just know presum-k That's enough , Add presum-k The number of
adopt map To maintain a prefix and The number of
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int,int> map;
map[0]=1;// Prefixes and are 0 The number of 1
int preSum=0;
int count=0;
for(int num:nums){
preSum+=num;
if(map.count(preSum-k)){
// Add prefix and as preSum-k The number of
count+=map[preSum-k];
}
map[preSum]++;
}
return count;
}
};
边栏推荐
猜你喜欢

JMeter loop controller and CSV data file settings are used together

Adb 实用命令(网络包、日志、调优相关)
![[second on] [jeecgboot] modify paging parameters](/img/59/55313e3e0cf6a1f7f6b03665e77789.png)
[second on] [jeecgboot] modify paging parameters

PDF文档签名指南

【acwing】786. 第k个数

1321:【例6.3】删数问题(Noip1994)

Fiddler break point

LLVM之父Chris Lattner:為什麼我們要重建AI基礎設施軟件

Postman interface test IV

XML configuration file parsing and modeling
随机推荐
Fiddler simulates the interface test
STM32 ADC和DMA
mysql插入数据创建触发器填充uuid字段值
MCU is the most popular science (ten thousand words summary, worth collecting)
求方程ax^2+bx+c=0的根(C语言)
Jump to the mobile terminal page or PC terminal page according to the device information
浅谈日志中的返回格式封装格式处理,异常处理
学习记录——高精度加法和乘法
Sword finger offer 38 Arrangement of strings [no description written]
fiddler-AutoResponder
ORM model -- creation and query of data records
柏拉图和他的三个弟子的故事:如何寻找幸福?如何寻找理想伴侣?
IIC基本知识
1323:【例6.5】活动选择
2022.7.4DAY596
Use the fetch statement to obtain the repetition of the last row of cursor data
leetcode-304:二维区域和检索 - 矩阵不可变
Adb 实用命令(网络包、日志、调优相关)
LLVM之父Chris Lattner:为什么我们要重建AI基础设施软件
原型与原型链