滑动窗口题型
滑动窗口类型的题目经常是用来执行数组或是链表上某个区间(窗口)上的操作。比如找最长的全为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.
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.
Follow Up:
Can you do it in O(n) time?
这道题给我们一个一维数组nums,让我们求和为k最大子数组,默认子数组必须连续,题目中提醒我们必须要在O(n)的时间复杂度完成
解题思路:
用一个变量sum边累加边处理,在map中保存第一个出现该累积和的位置,后面再出现直接跳过,这样算下来就是最长的子数组
class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k) {
if(nums.empty())return 0;//空值判断
int sum = 0, res = 0;
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); ++i) {
sum += nums[i];
if (sum == k) res = i + 1; //累加值与k进行对比
else if (m.count(sum - k)) res = max(res, i - m[sum - k]);//在m中查找符合条件的子数组首字节
if (!m.count(sum)) m[sum] = i;
}
return res;
}
};
参考:https://www.cnblogs.com/grandyang/p/5336668.html