滑动窗问题

##引言:
在面试中有一类问的比较多的问题–滑动窗问题滑动窗问题本质上属于双指针问题中的前向型双指针(一个方向的双指针)。

滑动窗口问题一般题目会很典型,要求我们一直维护一个size为k的window,然后do some operation/calculate
something within that
window。基本思路就是每次不管三七二十一先把当前新的元素加进来,然后如果有需要(比如有元素过期了)移除出来,这时我们可以确保现在maintain的是一个valid
window。真正的logic happens here。

Tips:

稍微需要考虑的变种有固定滑动窗可变滑动窗

分析:

从以上的描述可以看出,滑动窗问题套路是一致的,主要搞清楚什么时候才是有效的滑动窗,还有对于移进来的滑动窗口怎么处理,对于移出的滑动窗口如何处理。
另外注意一点,滑动窗的size不一定是固定值,有时候求最小长度,就是求滑动窗的大小。但是所有的操作都是在valid Window中进行的,并且还要maintain这个valid Window.
##例题

因为我们要maintain一个size为k的window,除了上述的算法层面的操作,我们还需要考虑使用什么容器去hold那些元素。这里常见的容器有:

  • Queue (First in First out behavior)
  • Deque (双端都可以操作)
  • Stack (一般是单调栈的应用)
  • Heap(求max/min, first k max/mins, median)
    我这里补充一个在String中常用的是HashMap…

1.Minimum Window Substring
分析:这个题目是要求在源字符串中包含目标字符串的最短“子串”,这里的子串我注明了引号,因为不同问题定义的方式不同。这类求子串问题是要打表的,变窗口滑动窗。
需要注意得是这里的有效滑动窗(即什么叫子串匹配)
Code:

public class Solution {
    public String minWindow(String s, String t) {
        int len1 = s.length();
        int len2 = t.length();
        if (len2 > len1) {
            return "";
        }
        int[] targethash = new int[256];
        int[] sourcehash = new int[256];
        int ans = Integer.MAX_VALUE;
        String minStr = "";
        initHash(targethash, t);
        int i = 0;
        int j = 0;
        for (i = 0; i < len1; i++) {
            while (!valid(targethash, sourcehash) && j < len1) {
                    if (j < len1) {
                    sourcehash[s.charAt(j)]++;
                    j++;
                    } else {
                        break;
                    }
                
            }
            if(valid(targethash, sourcehash) ){
                
                    if (ans > j - i) {
                    ans = Math.min(ans, j - i );
                    minStr = s.substring(i, j );
                        
                    }
                
            }

            sourcehash[s.charAt(i)]--;
            
        }
        return minStr;
        
        
        
    }
    
    private void initHash(int[] targethash, String Target) {
        char[]charArray = Target.toCharArray();
        for (char ch : charArray) {
            targethash[ch]++;
        }
    }
    private boolean valid(int[] targethash, int[] sourcehash) {
        for (int i = 0; i < 256; i++) {
            if (targethash[i] > sourcehash[i]) {
                return false;
            }
        }
        return true;
    }
}

2.Permutation in String
分析:
判断源字符串中是否有目标字符串的某个排列,基本思路打表,并且这个问题为固定滑动窗问题。
Code:

public class Solution {
    public boolean checkInclusion(String s1, String s2) {
        int len1 = s1.length();
        int len2 = s2.length();
        if (len1 > len2) {
            return false;
        }
        int[] target = new int[26];
        
        for (int i = 0; i < len1; i++) {
            target[s1.charAt(i) - 'a']++;
            target[s2.charAt(i)- 'a']--;
        }
        if (allZeros(target)) {
            return true;
        }
        for (int i = len1; i < len2; i++) {
            target[s2.charAt(i) - 'a']--;
            target[s2.charAt(i - len1) - 'a']++;
            if (allZeros(target)) {
                return true;
            }
        }
        return false;
    }
    private boolean allZeros(int[] target) {
        for (int i = 0; i < 26; i++) {
            if (target[i] != 0) {
                return false;
            }
        }
        return true;
    }
}

3.Minimum Size Subarray Sum
问题分析:在原数组中找到最短子数组,满足sum >= s,同样也是滑动窗,只不过匹配的方式(有效滑动窗的方式)变了,另外注意移出滑动窗的处理方式以及异常情况最后的判断。
Code:

public class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int i = 0;
        int j = 0;
        int sum = 0;
        int ans = Integer.MAX_VALUE;
        for (i = 0; i < nums.length; i++) {
            while (j < nums.length && sum < s) {
                sum += nums[j];
                j++;
            }
            if (sum >= s) {
                ans = Math.min(ans, j - i);
            }
            sum -= nums[i];
        }
        return ans == Integer.MAX_VALUE ? 0 : ans;
    }
}

4.Find All Anagrams in a String
分析:找出源字符串中所以目标字符串排列组合的索引位置,思路也是滑动窗,打表写好匹配方式。
Code:

public class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        int len1 = s.length();
        int len2 = p.length();
        List<Integer> res = new ArrayList<>();
        if (len2 > len1) {
            return res;
        }
        int[] targethash = new int[26];
        int[] sourcehash = new int[26];
        initHash(targethash, p);
        for (int i = 0; i < len2; i++) {
            sourcehash[s.charAt(i) - 'a']++;
        }
        if (valid(targethash, sourcehash)) {
            res.add(0);
        }
        for (int i = len2; i < len1; i++) {
            sourcehash[s.charAt(i) - 'a']++;
            sourcehash[s.charAt(i - len2) - 'a']--;
            if (valid(targethash, sourcehash)) {
                res.add(i - len2 + 1);
            }
        }
        return res;

    }
    private void initHash(int[] targethash, String target) {
        char[] charArray = target.toCharArray();
        for (char ch : charArray) {
            targethash[ch - 'a']++;
        }
    }
    private boolean valid(int[] targethash, int[] sourcehash) {
        for (int i = 0; i < 26; i++) {
            if (targethash[i] != sourcehash[i]) {
                return false;
            }
        }
        return true;
    }
}

5.Sliding Window Maximum
分析:这题的解法是不是滑动窗不好界定,用了双端队列(Deque)…
在[i - (k - 1) , i]中得到候选元素。Deque的头用来维持 valid Window,Deque的尾用来排除掉不可能的候选元素。
Code:

 public class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        
        if (nums.length == 0 && k == 0){
            return new int[0];
        }
      
        int len = nums.length;
        int index = 0;
        int[] res = new int[len - (k - 1)];
        Deque<Integer> q = new  ArrayDeque<Integer>();
        for (int i = 0; i < nums.length; i++) {
            //maintain the valid window
            while (!q.isEmpty() && q.peekFirst() < i - (k - 1)){
                q.pollFirst();
            }
            //remove unuseful candicate
            while (!q.isEmpty() && nums[q.peekLast()] < nums[i]){
                q.pollLast();
            }
            q.offerLast(i);
            
            //save the result
            if (i >= k - 1){
                res[index++] = nums[q.peekFirst()];
            }
        }
        return res;
    }
}

6.滑动窗口内数的和
分析:固定滑动窗,全裸。
Code:

public class Solution {
    /**
     * @param nums a list of integers.
     * @return the sum of the element inside the window at each moving.
     */
    public int[] winSum(int[] nums, int k) {
        // write your code here
        int n = nums.length;
        if (nums == null || nums.length == 0 || k <= 0 || k > nums.length){
            return new int[0];
        }
        
        int[] sum = new int[n - k + 1];
        
        for (int i = 0; i < k; i++){
            sum[0] += nums[i];
        }
        
        for (int j = 1; j < n - k + 1; j++){
            sum[j] = nums[j + k - 1] + sum[j - 1] - nums[j - 1];
        }
        
        return sum;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值