Prove safety Offer: maximum sliding window (java version)

Title Description

Given an array and the size of the sliding window, sliding window to find the maximum value among all values.
For example, if the input array size and {2,3,4,2,6,2,5,1} 3 sliding window, then the presence of a total of six sliding window, their maximum values is {4,4,6, 6,6,5};
it has the following six array {2,3,4,2,6,2,5,1} for the sliding window: {[2,3,4], 2,6,2,5 , 1}, {2, [3,4,2], 6,2,5,1}, {2,3, [4,2,6], 2, 5},
{2,3,4 , [2,6,2], 5,1}, {2,3,4,2, [6,2,5], 1}, {2,3,4,2,6, [2,5, 1]}.
Note: When the size> length of the array, that no maximum value

Traversal number in the window

Each slide once, traversing all the numbers in the current window, looking to play the maximum

import java.util.*;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size){
        ArrayList<Integer> res = new ArrayList<>();
        if(num==null || num.length==0 || size==0 || size>num.length) 
            return res;
        for(int i=0; i+size-1<num.length; i++){
            res.add(maxNum(num, i, i+size-1 ));
        }
        return res;
    }
    private int maxNum(int[] num, int L, int R){
        int max = num[L];
        for(int i = L;i<=R;i++){
            if(num[i] > max){
                max = num[i];
            }
        }
        return max;
    }
}

Use deque

Team head used to record the maximum value of the current window, adding to the tail number, start comparing newly added value from the tail, all smaller than the value of his lost (because the current number is added later, and also than the tail large numbers, the number of the tail can not be the maximum value within the window).
Returns the maximum value from the beginning of the first team, first determine whether or not expired (not within the window), delete outdated.

import java.util.*;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size){
        ArrayList<Integer> res = new ArrayList<Integer>();
        if(num==null || num.length==0 || size==0 || size>num.length)
            return res;
        LinkedList<Integer> list = new LinkedList<Integer>();
        for(int i=0; i<size-1; i++){ // 先添加0-size-1个数,此时不输出最大值
            while(!list.isEmpty() && num[list.getLast()]<num[i]){
                list.removeLast();
            }
            list.add(i);
        }
        for(int i=size-1; i<num.length; i++){ // 此时开始输出最大值
            while(!list.isEmpty() && num[list.getLast()] < num[i]){
                list.removeLast();
            }
            list.add(i);
            while(list.getFirst()+size-1 < i){ // 判断队头元素是否过期
                list.removeFirst();
            }
            res.add(num[list.getFirst()]);
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/qq_43165002/article/details/90667188