[LeetCode] Maximum Size Subarray Sum Equals k 最大子数组之和为k
Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead.
Note:
The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.
Example 1:
Input: nums =[1, -1, 5, -2, 3], k =3
Output: 4
Explanation: The subarray[1, -1, 5, -2]sums to 3 and is the longest.
Example 2:
Input: nums =[-2, -1, 2, 1], k =1
Output: 2
Explanation: The subarray[-1, 2]sums to 1 and is the longest.
Follow Up:
Can you do it in O(n) time?
这道题给我们一个一维数组nums,让我们求和为k最大子数组,默认子数组必须连续,题目中提醒我们必须要在O(n)的时间复杂度完成,我试了下brute force无法通过OJ,那么根据题目中的提示标签,我们需要用哈希表和累积和来做,关于累积和的用法可以参看我之前的博客Range Sum Query - Immutable,那么建立累积和的好处显而易见,如果当前累积和正好等于k,那么从开头到此位置的子数组就是一个符合要求的解,但不一定是最长的子数组,而使用哈希表来建立累积和和其坐标之间的映射,我们就从题目中给的例子进行分析:
nums: [1, -1, 5, -2, 3], k = 3
sums: [1, 0, 5, 3, 6]
我们可以看到累积和的第四个数字为3,和k相同,则说明前四个数字就是符合题意的一个子数组,再来看第二个例子:
nums: [-2, -1, 2, 1], k = 1
sums: [-2, -3, -1, 0]
我们发现累积和中没有数字等于k,但是我们知道这个例子的答案是[-1, 2],那么我们看累积和数组的第一和第三个数字,我们是否能看出一些规律呢,没错,第三个数字-1减去k,得到第一个数字,这就是规律,这也是累积和求区间和的方法,但是由于累计和数组中可能会有重复数字,而哈希表的关键字不能相同,比如下面这个例子:
nums: [1, 0, -1], k = -1
sums: [1, 1, 0]
我们发现累积和数组的第一个和第二个数字都为1,那么如何建立映射呢,我想的是用一个一维数组将其都存起来,然后比较的话就比较数组中的第一个数字,当我们建立完哈希表后,开始遍历这个哈希表,当累积和跟k相同时,我们更新res,不相同的话我们检测当前值减去k得到的值在哈希表中存不存在,如果存在就更新结果,参见代码如下:
解法一:
class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k) {
if (nums.empty()) return ;
int res = ;
unordered_map<int, vector<int>> m;
m[nums[]].push_back();
vector<int> sum = nums;
for (int i = ; i < nums.size(); ++i) {
sum[i] += sum[i - ];
m[sum[i]].push_back(i);
}
for (auto it : m) {
if (it.first == k) res = max(res, it.second.back() + );
else if (m.find(it.first - k) != m.end()) {
res = max(res, it.second.back() - m[it.first - k][]);
}
}
return res;
}
};
然而当我上网看大神们的解法时,才发现我图样图森破,根本不需要我写的那么复杂,我们不需要另外创建一个累积和的数组,而是直接用一个变量sum边累加边处理,而且我们哈希表也完全不用建立和一维数组的映射,只要保存第一个出现该累积和的位置,后面再出现直接跳过,这样算下来就是最长的子数组,对于想出这解法的人,博主只想说,阁下何不随风起,扶摇直上九万里~参见代码如下:
解法二:
class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k) {
int sum = , res = ;
unordered_map<int, int> m;
for (int i = ; i < nums.size(); ++i) {
sum += nums[i];
if (sum == k) res = i + ;
else if (m.count(sum - k)) res = max(res, i - m[sum - k]);
if (!m.count(sum)) m[sum] = i;
}
return res;
}
};
类似题目:
参考资料:
https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/
https://leetcode.com/discuss/77879/o-n-super-clean-9-line-java-solution-with-hashmap
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Maximum Size Subarray Sum Equals k 最大子数组之和为k的更多相关文章
- LeetCode Maximum Size Subarray Sum Equals k
原题链接在这里:https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/ 题目: Given an array nums an ...
- leetcode 560. Subarray Sum Equals K 、523. Continuous Subarray Sum、 325.Maximum Size Subarray Sum Equals k(lintcode 911)
整体上3个题都是求subarray,都是同一个思想,通过累加,然后判断和目标k值之间的关系,然后查看之前子数组的累加和. map的存储:560题是存储的当前的累加和与个数 561题是存储的当前累加和的 ...
- Subarray Sum & Maximum Size Subarray Sum Equals K
Subarray Sum Given an integer array, find a subarray where the sum of numbers is zero. Your code sho ...
- Subarray Sum & Maximum Size Subarray Sum Equals K && Subarray Sum Equals K
Subarray Sum Given an integer array, find a subarray where the sum of numbers is zero. Your code sho ...
- [LeetCode] 325. Maximum Size Subarray Sum Equals k 和等于k的最长子数组
Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If t ...
- Maximum Size Subarray Sum Equals k -- LeetCode
Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If t ...
- 【LeetCode】325. Maximum Size Subarray Sum Equals k 解题报告 (C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 prefix Sum 日期 题目地址:https:// ...
- [Locked] Maximum Size Subarray Sum Equals k
Example 1: Given nums = [1, -1, 5, -2, 3], k = 3,return 4. (because the subarray [1, -1, 5, -2] sums ...
- Maximum Size Subarray Sum Equals k LT325
Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If t ...
随机推荐
- SSE指令集学习:Compiler Intrinsic
大多数的函数是在库中,Intrinsic Function却内嵌在编译器中(built in to the compiler). 1. Intrinsic Function Intrinsic Fun ...
- 利用Python进行数据分析(8) pandas基础: Series和DataFrame的基本操作
一.reindex() 方法:重新索引 针对 Series 重新索引指的是根据index参数重新进行排序. 如果传入的索引值在数据里不存在,则不会报错,而是添加缺失值的新行. 不想用缺失值,可以用 ...
- [占位-未完成]scikit-learn一般实例之十二:用于RBF核的显式特征映射逼近
It shows how to use RBFSampler and Nystroem to approximate the feature map of an RBF kernel for clas ...
- [下载]北京新版小学英语五年级上册mp3点读APP
义务教育教科书小学英语五年级上册点读软件.根据2014年北京教改版教材编写,发音标准.实现点读功能.点到哪里读到哪里.哪里不会点哪里!北京教育科学研究院编写,北京出版社出版.ISBN:97872001 ...
- querystring模块
querystring处理参数的小利器. 下面是querystring的四个方法. ①stringify:将一个参数对象序列化为一个字符串 eg: querystring.stringify({n ...
- 企业IT架构介绍
企业信息化之路 问题 互联互通 统一访问 统一身份管理 数据管理模型 企业数据集成业务架构 业务流程框架 业务流程模型 个性流程支持 跨业务的业务流程组合 EBS总线 ] SOA架构上视图 B ...
- Eclipse 日期和时间格式自定义
点击下载Eclipse插件 org.eclipse.text_3.5.300.v20130515-1451.jar 覆盖下图所示的jar文件. /************************* ...
- Maven实战系列文章
1.Maven命令行使用:mvn clean compile(编译) 2.Maven命令行使用:mvn clean package(打包) 3.Maven命令行使用:mvn clean install ...
- 异常:java.lang.LinkageError: loader constraint violation: when resolving interface method
异常:java.lang.LinkageError: loader constraint violation: when resolving interface method "javax. ...
- 转 threejs中3D视野的缩放实现
Threejs基础部分学习知道透视相机new THREE.PerspectiveCamera(fov, aspect , near,far)中. fov视野角(拍摄距离)越大,场景中的物体越小.fov ...