66. A sliding window maximum

Subject 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]}.

Analysis of ideas:

  Is provided for storing a queue element index, the index of the first element into a queue number, and then starts the second element through the array, if the value of the current element is less than the lower end of the queue stored in the element corresponding to subscript value, then the index of the current element added to the tail, if greater than the end of the queue stored in the index corresponding to the value of the element, the end of the queue pop up, until the current element is smaller than the end of the queue stored in the index value of the element corresponding to the then current element corresponding to subscript added to the end of the queue, when traversing the element index i is greater than the window size minus one, the corresponding element of index is the head of the queue store window maximum, to be noted that, when the value is equal to i-size queue head when the value stored in index, has proved this time window does not include an element corresponding to subscript stored in the queue head, it should pop up at this time the queue head.

Code:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
        ArrayList<Integer>res=new ArrayList<>();
        if(num==null||num.length==0||num.length<size||size<1)
            return res;
        LinkedList<Integer>q=new LinkedList<>(); //存放下标
        for(int i=0;i<num.length;i++){
            while(!q.isEmpty()&&num[i]>=num[q.peekLast()]){
                    q.pollLast(); //当前遍历到的元素大于等于队列尾元素,队列尾部元素弹出,直到小于队列尾元素。
                }
                q.addLast(i);
            
            if(q.peekFirst()==i-size)//如果当前窗口已经不包含队列头下标对应的元素那么我们就要去掉它。
                q.pollFirst();
            if(i>=size-1){//当i大于窗口大小减一时,开始输出窗口中的最大值。
                res.add(num[q.peekFirst()]);
            }
        }
        return res;
    }
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/10962633.html