[leetcode] 325. Maximum Size Subarray Sum Equals k 解题报告
2016-03-06 05:50
567 查看
题目链接:https://leetcode.com/problems/maximum-size-subarray-sum-equals-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.
Example 1:
Given nums =
return
Example 2:
Given nums =
return
Follow Up:
Can you do it in O(n) time?
思路:时间复杂度为O(n^2)的思路比较好想,O(n)的想了好久没想到怎么做,后来才知道可以用hash表来保存以往的和,然后每次去查是否当前和减去目标值已经存在, 是的话说明我们找到了一个序列,然后更新最大长度大小.另外一个需要注意的是初始值.当什么都不拿时位置设为-1.
代码如下:
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.
Example 1:
Given nums =
[1, -1, 5, -2, 3], k =
3,
return
4. (because the subarray
[1, -1, 5, -2]sums to 3 and is the longest)
Example 2:
Given nums =
[-2, -1, 2, 1], k =
1,
return
2. (because the subarray
[-1, 2]sums to 1 and is the longest)
Follow Up:
Can you do it in O(n) time?
思路:时间复杂度为O(n^2)的思路比较好想,O(n)的想了好久没想到怎么做,后来才知道可以用hash表来保存以往的和,然后每次去查是否当前和减去目标值已经存在, 是的话说明我们找到了一个序列,然后更新最大长度大小.另外一个需要注意的是初始值.当什么都不拿时位置设为-1.
代码如下:
class Solution { public: int maxSubArrayLen(vector<int>& nums, int k) { if(nums.size() ==0) return 0; unordered_map<int, int> hash; hash[0] = -1; int sum =0, result = 0; for(int i =0; i< nums.size(); i++) { sum += nums[i]; if(hash.find(sum)== hash.end()) hash[sum] = i; if(hash.find(sum-k) != hash.end()) result = max(result, i-hash[sum-k]); } return result; } };参考:https://leetcode.com/discuss/86319/sharing-my-100ms-simple-c-solution
相关文章推荐
- C语言程序设计
- 如何设置约束让三个按钮平分UIView容器的宽度
- C语言数据类型
- 55. Jump Game
- 思考下:工作沟通工具的选择(QQ?、微信?、邮件?、m2m还是其他的?)
- c语言题中的一些陷阱
- 只需2个公式,3阶魔方7步还原法
- [leetcode] 297. Serialize and Deserialize Binary Tree 解题报告
- 夺命雷公狗---微信开发44----用户分组管理接口(实例)
- 插入排序法 php
- 自定义一个只显示年月的DatePicker(UIDatePicker无法实现年月显示)
- 分支限界法求解旅行商问题
- 观察者模式
- Sublime test配置php运行环境
- FLC-Regular Grammar
- LeetCode Reverse Words in a String II
- 64位Ubuntu使用john破解密码的No password hashes loaded
- 关于JAVA中的Synchronization和interface误用
- leetcode50 Pow(x, n)
- 召回率与准确率概念