911. 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
Example1
Input: nums = [1, -1, 5, -2, 3], k = 3
Output: 4
Explanation:
because the subarray [1, -1, 5, -2] sums to 3 and is the longest.
Example2
Input: nums = [-2, -1, 2, 1], k = 1
Output: 2
Explanation:
because the subarray [-1, 2] sums to 1 and is the longest.
Challenge
Can you do it in O(n) time?
Notice
The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.
解法1:presums + hashmap
先构建presums数组,然后就可以转换成一个数组里面找两个数之差等于k的问题了。
这个问题可以用同向双指针,也可以用hashmap。
注意,我们要考虑某个数本身就是k和某个presum本身就是k这两种特殊情况,因为presums里面两个元素相减的差并不会考虑头一个元素,所以会漏掉presum的情况。
class Solution {
public:
/**
* @param nums: an array
* @param k: a target value
* @return: the maximum length of a subarray that sums to k
*/
int maxSubArrayLen(vector<int> &nums, int k) {
int n = nums.size();
if (n == 0) return 0;
vector<int> presums(n);
int maxLen = 0;
presums[0] = nums[0];
if (nums[0] == k) maxLen = 1;
for (int i = 1; i < n; ++i) {
presums[i] = presums[i - 1] + nums[i];
if (nums[i] == k) maxLen = max(maxLen, 1);
if (presums[i] == k) maxLen = max(maxLen, i + 1);
}
unordered_map<int, int> hashMap; //value, index
for (int i = 0; i < n; ++i) {
int temp = presums[i] - k;
if (hashMap.find(temp) != hashMap.end()) {
maxLen = max(maxLen, i - hashMap[temp]);
}
if (hashMap.find(presums[i]) == hashMap.end()) hashMap[presums[i]] = i;
}
return maxLen;
}
};
解法2:presumes + two pointer (同向)
注意!这题不能用同向双指针(滑动窗口)!因为测试用例里面有负数!下面这个链接讲的很好。
算法学习-滑动窗口_滑动窗口处理-CSDN博客