当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢

ORM -- grouping query, aggregation query, query set queryset object properties

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

Review of the losers in the postgraduate entrance examination

OpenGL glLightfv 函数的应用以及光源的相关知识

SQLyog数据库怎么取消自动保存更改

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

Postman interface test VI

Postman interface test IV

浅谈日志中的返回格式封装格式处理,异常处理

JMeter installation
随机推荐
CONDA creates virtual environment offline
Pdf document signature Guide
555电路详解
Postman interface test II
[sword finger offer] 42 Stack push in and pop-up sequence
The story of Plato and his three disciples: how to find happiness? How to find the ideal partner?
Learning records - high precision addition and multiplication
基于gis三维可视化技术的智慧城市建设
Programming features of ISP, IAP, ICP, JTAG and SWD
对存储过程进行加密和解密(SQL 2008/SQL 2012)
Postman interface test III
fiddler-AutoResponder
HAL库配置通用定时器TIM触发ADC采样,然后DMA搬运到内存空间。
[email protected]能帮助我们快速拿到日志对象
Prototype object in ES6
The method of word automatically generating directory
UnityWebRequest基础使用之下载文本、图片、AB包
JMeter loop controller and CSV data file settings are used together
MCU与MPU的区别
Talking about the return format in the log, encapsulation format handling, exception handling