天天看點

[劍指offer] 滑動視窗的最大值

本文首發于我的個人部落格:[尾尾部落]( https://weiweiblog.cn/maxinwindows/

題目描述

給定一個數組和滑動視窗的大小,找出所有滑動視窗裡數值的最大值。例如,如果輸入數組{2,3,4,2,6,2,5,1}及滑動視窗的大小3,那麼一共存在6個滑動視窗,他們的最大值分别為{4,4,6,6,6,5}; 針對數組{2,3,4,2,6,2,5,1}的滑動視窗有以下6個: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。

解題思路

法一:簡單的暴力法

法二:雙向隊列

用一個雙向隊列,隊列第一個位置儲存目前視窗的最大值,當視窗滑動一次,判斷目前最大值是否過期(目前最大值的位置是不是在視窗之外),新增加的值從隊尾開始比較,把所有比他小的值丢掉。這樣時間複雜度為O(n)。

參考代碼

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
        ArrayList<Integer> res = new ArrayList<Integer>();
        if(num.length < size || size == 0)
            return res;
        for(int i = 0; i < num.length - size + 1; i++){
            res.add(max(num, i, size));
        }
        return res;
    }
    public int max(int [] num, int index, int size){
        int res = num[index];
        for(int i = index + 1; i < index + size; i++){
            if(num[i] > res)
                res = num[i];
        }
        return res;
    }
}
           
import java.util.ArrayList;
import java.util.LinkedList;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size){
        ArrayList<Integer> res = new ArrayList<Integer>();
        LinkedList<Integer> deque = new LinkedList<Integer>();
        if(num.length == 0 || size == 0)
            return res;
        for(int i = 0; i < num.length; i++){
            if(!deque.isEmpty() && deque.peekFirst() <= i - size)
                deque.poll();
            while(!deque.isEmpty() && num[deque.peekLast()] < num[i])
                deque.removeLast();
            deque.offerLast(i);
            if(i + 1 >= size)
                res.add(num[deque.peekFirst()]);
        }
        return res;
    }
}