当前位置:   article > 正文

LeetCode刷题 --- 滑动窗口_leetcode 滑动窗口

leetcode 滑动窗口

滑动窗口法

        也叫尺取法(可能也不一定相等,大概就是这样),可以用来解决一些查找满足一定条件的连续区间的性质(长度等)的问题。由于区间连续,因此当区间发生变化时,可以通过旧有的计算结果对搜索空间进行剪枝,这样便减少了重复计算,降低了时间复杂度。往往类似于“请找到满足xx的最x的区间(子串、子数组)的xx这类问题都可以使用该方法进行解决。

核心思路

形成窗口,窗口实际上是两个指针之间形成的区域,关键点就是这两个指针如何进行移动(一般经验是,右指针无脑移动,左指针根据条件移动)

典型例题

​​​​​​209. 长度最小的子数组

题目:

        找到改数组中满足和 “大于等于”target的长度最小的,连续子数组。

分析:

        采用滑动窗口,左指针不动,右指针不断滑动,计算sum,当sum>=target时,计算当前窗口的长度;

        然后右指针不动,左指针滑动,一直到sum<target时,跳出内层循环,进行下一次循环

        然后还是先移动右指针,在移动左指针...

代码

  1. public static int minSubArrayLen1(int target, int[] nums) {
  2. // 定义左右指针
  3. int left = 0;
  4. int rigth = 0;
  5. // 定义一个sum变量,保存滑动窗口中的所有和
  6. int sum = 0;
  7. // 定义变量保存窗口最小的宽度,初始值设置为int类型最大值
  8. int res = Integer.MAX_VALUE;
  9. // 外层循环,右指针移动
  10. while (rigth < nums.length) {
  11. sum += nums[rigth];
  12. // 内层循环,左指针移动
  13. while (sum >= target) {
  14. res = Math.min(res, rigth - left + 1);
  15. sum -= nums[left];
  16. left++;
  17. }
  18. rigth++;
  19. }
  20. return res == Integer.MAX_VALUE ? 0 : res;
  21. }
  1. class Solution:
  2. def minSubArrayLen(self, target: int, nums: List[int]) -> int:
  3. left, right = 0, 0
  4. res, sum = len(nums) + 1, 0
  5. while right < len(nums):
  6. sum += nums[right]
  7. while sum >= target:
  8. res = min(res, right - left + 1)
  9. sum -= nums[left]
  10. left += 1
  11. right += 1
  12. return res if res < len(nums) else 0

3. 无重复字符的最长子串

题目

        找出字符串中不含有重复字符的最长子串长度。

分析

        还是滑动窗口解决。

代码

  1. public static int lengthOfLongestSubstring1(String s) {
  2. // 字符串转为数组方便遍历
  3. char[] chars = s.toCharArray();
  4. // 定义左右指针
  5. int left = 0;
  6. int rigth = 0;
  7. // 定义res保存不重复的数字的最大长度,初始值设为0;
  8. int res = 0;
  9. // 定义一个set集合,判断是否有重复字母
  10. Set<Character> set = new HashSet<>();
  11. // 外层循环,右指针移动
  12. while (rigth < chars.length) {
  13. // 内层循环,左指针移动
  14. // 如果set中已经包含了即将右指针指的字符,说明这个字符已经有了,出现了重复
  15. // 重复了,就要把重复的字符移除掉,然后继续向右遍历
  16. while (set.contains(chars[rigth])) {
  17. set.remove(chars[left]);
  18. left++;
  19. }
  20. // 已经不包含重复的了,因此可以将右指针的字符放入
  21. set.add(chars[rigth]);
  22. // 计算滑动窗口长度
  23. res = Math.max(res, rigth - left + 1);
  24. rigth++;
  25. }
  26. return res;
  27. }
  1. class Solution:
  2. def lengthOfLongestSubstring(self, s: str) -> int:
  3. my_set = set()
  4. left, right = 0, 0
  5. res = 0
  6. while right < len(s):
  7. while s[right] in my_set:
  8. res = max(res, right - left)
  9. my_set.remove(s[left])
  10. left += 1
  11. my_set.add(s[right])
  12. right += 1
  13. if len(my_set) > res:
  14. res = len(my_set)
  15. return res

1004. 最大连续1的个数 III

题目

        给一个01的数组,和一个整数K,求允许反转K个0后,返回数组中连续为1的最大个数。

分析

        求连续为1的最大个数,很明显用滑动窗口,关键是滑动条件是怎么样的?

        题目允许最多反转K个0为1,那么就可以定义一个计数器,记录反转的数量,右指针指向的位置,遇到0,计数器加1,左指针指向的位置,遇到0,计数器减一

        循环条件:外层循环,右指针不超过边界,不断移动右指针

                          内层循环,计数器大于K,不断移动左指针

代码

  1. public static int longestOnes1(int[] nums, int k) {
  2. // 定义左右指针
  3. int left = 0;
  4. int rigth = 0;
  5. // 定义最终返回结果,(求最大值就初始化一个小值,求最小值就初始化一个大值)
  6. int res = 0;
  7. // 定义计数器,计算的是从0变成1的个数
  8. int count=0;
  9. // 外层循环
  10. while (rigth < nums.length) {
  11. // 遇到右指针指向0,就要变成1,count加1
  12. if (nums[rigth] == 0) {
  13. count++;
  14. }
  15. // 变成1的值多了,就要想办法减少
  16. //开启内存循环
  17. while (count > k) {
  18. // 左指针指向0的时候,计数器才可以减一
  19. if (nums[left] == 0) {
  20. count--;
  21. }
  22. left++;
  23. }
  24. // 循环过程中去res的大值
  25. res = Math.max(res, rigth - left +1);
  26. rigth++;
  27. }
  28. return res;
  29. }
  1. class Solution:
  2. def longestOnes(self, nums: List[int], k: int) -> int:
  3. left, right, res = 0, 0, 0
  4. while right < len(nums):
  5. if nums[right] == 0:
  6. k -= 1
  7. while k < 0:
  8. if nums[left] == 0:
  9. k += 1
  10. left += 1
  11. res = max(res, right - left)
  12. right += 1
  13. return res

1208. 尽可能使字符串相等

题目

        求字符串可以转化的最大长度

分析

        字符之间的转换的开销是|s[i] - t[i]|,因此只要计算出每个对应位置的开销,就可以转为最基本的滑动窗口问题。

代码

  1. public static int equalSubstring1(String s, String t, int maxCost) {
  2. // 定义一个新的数组,存放两个字符串对应位置转换的开销
  3. char[] sChars = s.toCharArray();
  4. char[] tChars = t.toCharArray();
  5. int[] costs = new int[sChars.length];
  6. for (int i = 0; i < sChars.length; i++) {
  7. costs[i] = Math.abs(sChars[i] - tChars[i]);
  8. }
  9. // 后续就是滑动窗口最基本的解题套路
  10. int left = 0;
  11. int right = 0;
  12. int result = 0;
  13. int cost = 0;
  14. while (right< costs.length) {
  15. cost += costs[right];
  16. while (cost > maxCost) {
  17. cost -= costs[left];
  18. left++;
  19. }
  20. result = Math.max(result, right - left +1);
  21. right++;
  22. }
  23. return result;
  24. }
  1. class Solution:
  2. def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
  3. left, right, res, cost = 0, 0, 0, 0
  4. def my_cost(i):
  5. return abs(ord(s[i]) - ord(t[i]))
  6. while right < len(s):
  7. cost += my_cost(right)
  8. while cost > maxCost:
  9. cost -= my_cost(left)
  10. left += 1
  11. res = max(res, right - left + 1)
  12. right += 1
  13. return res

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/276884
推荐阅读
相关标签
  

闽ICP备14008679号