1.前言
滑动窗口是一种在有序数据序列(如数组、字符串)中,
通过维护一个动态变化的 “窗口” 区间,
高效解决子序列 / 子数组问题的算法思想。
其核心是通过 “滑动” 调整窗口的边界(左、右指针),
避免重复计算,将暴力解法的时间复杂度从
O
(
n
2
)
O(n^2)
O(n2)优化到
O
(
n
)
O(n)
O(n)
接下来我们来详细学习他
2.例题详解
(1) 长度最小的子数组(Leetcode 2091)
例:传入nums[]和target, nums=[2,3,1,2,4,3],target=7
我们来分析一下
,滑动窗口主要是通过双指针来实现的
我们规定一个指针left和right

int left = 0;
int right = 0;
int n = nums.length;
接下来让right向右移动,可以定义一个变量s来记录目前的总和,然后在来一个ans记录答案
int n = nums.length;
int ans = n+1;
int s = 0;
int left = 0;
int right= 0;
现在开始移动



这是我们发现2+3+1+2>7,所以此时我们记录新的ans
然后到了这题最重要的一步
因为此时已经大于7了,所以如果
right继续向后移动
结果仍然大于7,所以无需向后
这个时候我们可以移动
left,缩小范围,也就是这样

如果此时仍然大于7(只是其他情况,与上图无关),我们就继续重复操作
总结一下
- 让
right向右遍历 - 如果这时的和大于
target,就移动left,然后改变ans - 如果移动后依旧大于,重复步骤
- 最后就找到最小的
ans
写出代码
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int n = nums.length;
int ans = n+1;
int s = 0;
int left = 0;
for(int right=0;right<n;right++){
s += nums[right];
while (s >= target){
ans = ((right-left+1)<ans) ? (right-left+1) : ans;
s -= nums[left];
left++;
}
}
return ans<=n ? ans : 0;
}
}
(2) 乘积小于K的子数组(Leetcode 7132)
这道题与上一道题的思路一样
只是我们需要思考一个点
从 [ a , b ] [a,b] [a,b]如果是满足,那么 [ a + 1 , b ] , [ a + 2 , b ] … [ b , b ] [a+1,b],[a+2,b]\dots[b,b] [a+1,b],[a+2,b]…[b,b]都是满足的
所以如果 [ a , b ] [a,b] [a,b]满足,那么 b − a + 1 b-a+1 b−a+1都满足
只是相对上一个题多了一个统计次数而已
class Solution {
public int numSubarrayProductLessThanK(int[] nums, int k) {
if(k<=1){
return 0;
}
int left = 0;
int right = 0;
int ans = 0;
int prod = 1;
for(right=0;right<nums.length;right++){
prod *= nums[right];
while(prod>=k){
prod /= nums[left];
left ++;
}
ans += right-left+1;
}
return ans;
}
}
(3) 无重复字符的最长子串(Leetcode 33)
这里创新的部分就是要记录每个字符出现的次数,可以使用哈希表
我这里使用python,因为内置Counter4,其他语言就用哈希表
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
ans = 0
cnt = Counter()
left = 0
for right, c in enumerate(s):
cnt[c] += 1
while cnt[c] > 1:
cnt[s[left]] -= 1;
left += 1;
ans = max(ans, right-left+1)
return ans
3.总结
这是我第一次写博客,希望大家支持一下
有什么想要讲的可以私信我哦
https://leetcode.cn/problems/minimum-size-subarray-sum/description/ ↩︎
http://leetcode.cn/problems/subarray-product-less-than-k/description/ ↩︎
https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/ ↩︎
https://blog.youkuaiyun.com/qq_22866291/article/details/145950566 ↩︎
1518

被折叠的 条评论
为什么被折叠?



