当前位置:网站首页>leetcode:325. 和等于k的最长子数组长度
leetcode:325. 和等于k的最长子数组长度
2022-08-09 22:01:00 【OceanStar的学习笔记】
题目来源
题目描述
class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k){
}
};
题目解析
思路
- 先生成一个前缀和数组preSum,其长度为N + 1
- 那么,如果存在两个索引 i i i和 j j j,使得 p r e S u m [ j ] − p r e S u m [ i ] = = k preSum[j] - preSum[i] == k preSum[j]−preSum[i]==k,说明找到一个子数组 [ i , j − 1 ] [i, j - 1] [i,j−1],子数组和为k
- 因为要求长度最长,所以定义一个map,其key=preSum[i],value=i。如果存在同样的preSum[i],那么保存i较小的哪一个
- 然后遍历map,找可能的值
class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k){
int N = nums.size();
std::vector<int> preSum(N + 1, 0);
std::map<int, int> map;
preSum[0] = 0;
map[0] = 0;
for (int i = 1; i <= N; ++i) {
preSum[i] = nums[i - 1] + preSum[i - 1];
if(!map.count(preSum[i])){
map[preSum[i]] = i - 1;
}
}
int maxLen = 0;
for (int i = N; i > maxLen; --i) {
if(map.count(preSum[i] - k)){
maxLen = std::max(maxLen, i - map[preSum[i] - k]);
}
}
return maxLen;
}
};
简写
我们不需要另外创建一个累积和的数组,而是直接用一个变量sum边累加边处理,而且我们哈希表也完全不用建立和一维数组的映射,只要保存第一个出现该累积和的位置,后面再出现直接跳过,这样算下来就是最长的子数组
class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k){
int sum = 0, ans = 0;
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); ++i) {
sum += nums[i];
if(sum == k){
ans = i + 1;
}else if(m.count(sum - k)){
ans = std::max(ans, i - m[sum - k]);
}
if(!m.count(sum)){
m[sum] = i;
}
}
return ans;
}
};
测试
int main()
{
Solution solute;
vector<int> nums{
1, -1, 5, -2, 3};
int k=3;
cout<<solute.maxSubArrayLen(nums,k)<<endl;
return 0;
}
类似题目
- algorithm:XX. 和<=k的最长子数组的长度(无序整数数组) 前缀和 + 枚举所有子序列
- leetcode:209. 和>=k的最短子数组的长度(无序正数数组) 前缀和 + 二分
- leetcode:325. 和==k的最长子数组长度(无序整数数组) 前缀和 + 哈希
- leetcode:560. 和== K 的子数组的个数 前缀和 + 哈希
- leetcode:862. 和>=K的最短子数组长度
边栏推荐
- “稚晖君”为2022昇腾AI创新大赛打call&nbsp;期待广大开发者加入
- 接口自动化测试实践指导(上):接口自动化需要做哪些准备工作
- Common commands and technical function modules of Metasploit
- 第十七期八股文巴拉巴拉说(数据库篇)
- Bean life cycle
- navicat 快捷键
- Basic operations of openGauss database (super detailed)
- A1. Prefix Flip (Easy Version)
- Xiaohei's leetcode journey: 94. Inorder traversal of binary trees (supplementary Morris inorder traversal)
- Solution: Edu Codeforces 109 (div2)
猜你喜欢
随机推荐
大型分布式存储方案MinIO介绍,看完你就懂了!
OKR 锦囊妙计
leetcode 39. 组合总和(完全背包问题)
Flask's routing (app.route) detailed
D. Binary String To Subsequences
国内手机厂商曾为它大打出手,如今它却最先垮台……
unit test
阿里云架构师金云龙:基于云XR平台的视觉计算应用部署
Domestic mobile phone manufacturers once fought for it, but now it is the first to collapse...
In programming languages, the difference between remainder and modulo
Chatting embarrassing scenes, have you encountered it?Teach you to get the Doutu emoticon package with one click, and become a chat expert
【EF】数据表全部字段更新与部分字段更新
【EF】 更新条目时出错。有关详细信息,请参见内部异常。[通俗易懂]
shell学习
台风生成,广州公交站场积极开展台风防御安全隐患排查
【软考 系统架构设计师】案例分析④ 软件架构风格
Flask之路由(app.route)详解
华为鸿蒙3.0的野望:技术、应用、生态
1215 – Cannot add foreign key constraint
R语言检验时间序列的平稳性:使用tseries包的adf.test函数实现增强的Dickey-Fuller(ADF)检验、检验时序数据是否具有均值回归特性(平稳性)、不具有均值回归特性的案例