当前位置:网站首页>leetcode:560. 和为 K 的子数组
leetcode:560. 和为 K 的子数组
2022-06-29 03:21:00 【OceanStar的学习笔记】
题目来源
题目描述

class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
return process(nums, 0, k);
}
};
题目解析
双指针和滑动窗口使用的一个必要条件就是能一步一步迭代,确定窗口的收缩方向,这有负数,就完全不知道是左边缩小,还是右边缩小了
枚举
思路:把所有的子数组都穷举出来,算它们的和,看看谁的和等于k
枚举左右边界
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int len = nums.size();
int cnt = 0;
for (int left = 0; left < len; ++left) {
for (int right = left; right < len; ++right) {
int sum = 0;
for (int i = left; i <= right; ++i) {
sum += nums[i];
}
if(sum == k){
cnt++;
}
}
}
return cnt;
}
};

边枚举边计算(也超时了)
先固定起点,然后枚举右边界,时间复杂度降低了一维
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int len = nums.size();
int cnt = 0;
for (int left = 0; left < len; ++left) {
int sum = 0;
for (int right = left; right < len; ++right) {
sum += nums[right];
if(sum == k){
++cnt;
}
}
}
return cnt;
}
};

怎么优化呢?关键在于如何快速得到某个子数组的和,我们也可以用前缀和来解决
前缀和
什么是前缀和
对于一个给定的数组num,我们额外开辟一个前缀和数组进行预处理
int n = nums.length;
// 前缀和数组
std::vector<int> preSum(n + 1, 0);
preSum[0] = 0;
for (int i = 0; i < n; i++)
preSum[i + 1] = preSum[i] + nums[i];

preSum[i]就是nums[0..... i-1]的和。如果我们想要求nums[i...j]的和,只需要求preSum[j+1] - preSum[i]即可,而不需要重新去遍历数组了
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int len = nums.size();
// 构造前缀和
std::vector<int> preSum(len + 1);
preSum[0] = 0;
for (int i = 0; i < len; ++i) {
preSum[i + 1] = preSum[i] + nums[i];
}
int cnt = 0;
// 穷举所有子数组
for (int left = 0; left < len; ++left) {
for (int right = left; right < len; ++right) {
if(preSum[right + 1] - preSum[left] == k){
++cnt;
}
}
}
return cnt;
}
};
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
int len = nums.size();
// 构造前缀和
std::vector<int> preSum(len + 1);
preSum[0] = 0;
for (int i = 0; i < len; ++i) {
preSum[i + 1] = preSum[i] + nums[i];
}
int cnt = 0;
// 穷举所有子数组
for (int end = 1; end <= len; ++end) {
for (int start = 0; start < end; ++start) {
if(preSum[end] - preSum[start] == k){
++cnt;
}
}
}
return cnt;
}
};
还是超时了

前缀和 + 哈希
由于我们只关心次数,不关心具体的解,所以我们可以使用哈希表来加速运算。
主要思路:计算完包括了当前树前缀和之后,我们去查一查在当前树之前,有多少个前缀和等于preSum - k呢?
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
std::vector<int> preSum(nums.size() + 1);
preSum[0] = 0;
for (int i = 0; i < nums.size(); ++i) {
preSum[i + 1] = preSum[i] + nums[i];
}
std::unordered_map<int, int> map; // key 为前缀和,value为前缀和为key的个数,问题转化为和为k的问题
map[0] = 1;
int cnt = 0;
for (int i = 1; i < preSum.size(); ++i) {
if(map.count(preSum[i] - k)){
cnt = cnt + map[preSum[i] - k]; // 如果有与当前prefixSum[i]的差为k的,则加上它的个数
}
++map[preSum[i]];
}
return cnt;
}
};
用递归实现:
class Solution {
int process(vector<int>& nums, int target, int currSum, int idx, std::unordered_map<int, int> &map){
if(idx == nums.size()){
return 0;
}
//当前的前缀和
currSum += nums[idx];
int res = 0;
res += map[currSum - target];
++map[currSum];
res += process(nums, target, currSum, idx + 1, map);
return res;
}
public:
int subarraySum(vector<int>& nums, int k) {
std::unordered_map<int, int> map; // key 为前缀和,value为前缀和为key的个数,问题转化为和为k的问题
map[0] = 1;
return process(nums, k, 0, 0, map);
}
};
边栏推荐
- 测试入门——集成测试
- Restore the binary search tree [simulate according to the meaning of the question - > find the problem - > analyze the problem - > see the bidding]
- Redu.us took the initiative to transform, and the operation leader of China's charging pile emerged
- Laravel v. about laravel using the pagoda panel to connect to the cloud database (MySQL)
- VIM configuration and use
- 归并排序
- Kubernetes: container resource requirements and constraints (constraints)
- How does kubernetes store business data persistently? (10)
- Merge sort
- In the name of love, fresh e-commerce companies rush to sell flowers on Valentine's Day
猜你喜欢

In the name of love, fresh e-commerce companies rush to sell flowers on Valentine's Day

In depth analysis of Apache bookkeeper series: Part 3 - reading principle
![The continued movement of Jerry's watch [chapter]](/img/3e/f8b98997320580431a8e7117f4a506.jpg)
The continued movement of Jerry's watch [chapter]

Logarithmic calculation in reverse order, logarithmic calculation in sequence -- merge sort

蓝桥杯2022初赛——扫雷

问题——adb shellerror: insufficient permissions for device: verify udev rules.
![二叉树的层序遍历 II[层序遍历方式之一 ->递归遍历 + level]](/img/f9/efb73dd6047e6d5833581376904788.png)
二叉树的层序遍历 II[层序遍历方式之一 ->递归遍历 + level]

What is the gold content of the equipment supervisor certificate? Is it worth it?
![[issue 259] uncover how count is executed in MySQL?](/img/bc/ee26eba95f408ea887d6aa06301a0b.jpg)
[issue 259] uncover how count is executed in MySQL?
![[test theory] quality analysis ability](/img/4b/d011e16c7b2be52fe12c123214779e.jpg)
[test theory] quality analysis ability
随机推荐
问题——adb shellerror: insufficient permissions for device: verify udev rules.
1110: nearest common ancestor (function topic)
深度解析“链动2+1”模式的商业逻辑
Certification training | streamnational certification training phase 2
Stm32l4 Series MCU ADC accurately calculates input voltage through internal reference voltage
allegro 设计中显示网络飞线或关闭网络飞线的方法
matlab习题 —— 图像绘制练习
[linear algebra] 1.1 second and third order determinants
相同的树[从部分到整体]
問題——adb shellerror: insufficient permissions for device: verify udev rules.
Codeforces Round #771 (Div. 2) ABC
priority_ Understanding of queue
无法定位程序输入点 [email protected]
Jerry's watch begins to move [chapter]
map,set用pari作为key值,如何定义
In depth analysis of Apache bookkeeper series: Part 3 - reading principle
Nvisual helps integrators transform
快速排序,查询序列的第K大的数
Square root of X
測試入門——集成測試