当前位置:网站首页>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的最短子数组长度
边栏推荐
猜你喜欢

力扣 1413. 逐步求和得到正数的最小值

每日一R「02」所有权与 Move 语义

腾讯继续挥舞降本增效“大刀”,外包员工免费餐饮福利被砍了

Presto Event Listener开发

一文让你快速了解隐式类型转换【整型提升】!

阿里云架构师金云龙:基于云XR平台的视觉计算应用部署

Jinshanyun earthquake, the epicenter is in bytes?

Domestic mobile phone manufacturers once fought for it, but now it is the first to collapse...

五星控股汪建国:以“植物精神”深耕赛道,用“动物精神”推动成长

Xiaohei's leetcode journey: 94. Inorder traversal of binary trees (supplementary Morris inorder traversal)
随机推荐
台风生成,广州公交站场积极开展台风防御安全隐患排查
1215 – Cannot add foreign key constraint
工作经验-组件封装(拖拽排序组件)
Interviewer: How to deal with Redis big key?
Synchronization lock synchronized traces the source
SecureCRT sets the timeout period for automatic disconnection
POWER SOURCE ETA ETA Power Repair FHG24SX-U Overview
为什么这么多人都想当产品经理?
NodeJS使用JWT
The kvm virtual machine cannot be started, NOT available, and the PV is larger than the partition
【服务器数据恢复】SAN LUN映射出错导致文件系统数据丢失的数据恢复案例
FileZilla搭建FTP服务器图解教程
R语言ggplot2可视化:使用ggpubr包的ggscatter函数可视化散点图、使用scale_x_continuous函数的breaks参数指定X轴的断点的个数(设置参数n)
一文让你快速了解隐式类型转换【整型提升】!
Cesium渐变色3dtiles白模(视频)
R语言将列表数据转化为向量数据(使用unlist函数将列表数据转化为向量数据)
从源码方面来分析Fragment管理中 Add() 方法
【微服务~Nacos】Nacos服务提供者和服务消费者
Flask之路由(app.route)详解
A1. Prefix Flip (Easy Version)