滑动窗口Sliding Window Algorithm
应用及优点:
1.可用于解决数组或者字符串的子元素问题。
2.用单循环代替了嵌套循环问题,时间复杂度低。
3.用双指针维护动态窗口。
相关算法题:
Longest Substring Without Repeating Characters无重复最长子串
Find All Anagrams in a String(找到字符串中所有字母异位词)
Minimum Window Substring最小覆盖子串
209. Minimum Size Subarray Sum长度最小子数组
以“Find All Anagrams in a String”为例:
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.The order of output does not matter.
Example 1:
Input: s: "cbaebabacd" p: "abc" Output: [0, 6]
class Solution { public List<Integer> findAnagrams(String s, String p) { int [] need=new int[128]; int [] win=new int[128]; int left=0;int right=0; List<Integer> res=new ArrayList<>(); for(int i=0;i<p.length();i++){ need[p.charAt(i)]++;//将目标数组中各元素计数。 } while(right<s.length()){ win[s.charAt(right)]++;//窗口右移 while(right<s.length()&&win[s.charAt(right)]>need[s.charAt(right)]){//窗口停止右移条件 win[s.charAt(left)]--; left+;//窗口左移 } if(right-left+1==p.length()){ res.add(left); } right++; } return res; } }
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
维护固定长度的滑动窗口+查找表
class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { Set<Integer> s=new HashSet<>(); for(int i=0;i<nums.length;i++){ if(s.contains(nums[i])){ return true; } s.add(nums[i]); if(s.size()>k){ s.remove(nums[i-k]); } } return false; } }