[LeetCode-Difficult Question] 239. Maximum value of sliding window

Article directory

topic

Insert image description here

Method 1: Monotone deque

  if(deque.peekFirst() == nums[i - k])  deque.removeFirst();
  1. This step is critical. When the head element (the largest element) is the element to be discarded after the sliding window, it can no longer be the maximum value and must be removed.
  2. If the first element of the team (the largest element) is not an element abandoned by the sliding window, it will continue to serve as the maximum value (the first element of the team)

Problem solving steps:

  1. Build a double-ended alignment

  2. Build a window. If the current element to be pushed into the queue is larger than the tail element of the queue, the tail element will be popped out until the current element to be pushed into the stack is not larger than the tail element of the queue or the queue is empty before it can be added to the queue.
    Insert image description here

  3. Start sliding: When the head element (the largest element) of the queue is the element to be discarded after the sliding window, it can no longer be the maximum value and must be removed. Then if the current element to be pushed onto the stack is greater than the element at the tail of the queue, the tail element will be The element pops up and can only be added to the queue until the current element to be queued is no larger than the last element of the queue or the queue is empty.
    Insert image description here

  4. While processing, add the largest element of the window at the head of the queue to the result set.

class Solution {
    
    
    public int[] maxSlidingWindow(int[] nums, int k) {
    
    
        if(k==1) return nums;
        int[] res = new int[nums.length  -  k  +1];  //实现计算最后结果集的大小
        Deque<Integer>  deque = new LinkedList<>(); //双端队列   实现   单调队列
        //未形成窗口  --需要形成窗口
        for(int i = 0 ; i <k  ;  i++){
    
    
            //如果当前待入队元素大于队列尾部元素,则将尾部元素弹出  直到当前待入栈元素不大于队尾元素  或者队列为空 才能加入队列
            while(!deque.isEmpty() && nums[i] > deque.peekLast())   deque.removeLast();
            deque.addLast(nums[i]);//将当前元素入队
        }
        res[0] = deque.peekFirst();//获取第一个k位置的最大值
        int j = 1;
        for(int i = k ; i<nums.length; i++ ){
    
    
            //当队首元素(最大元素)是滑动窗口后要被抛弃的元素时,他就不能再是最大值了,就必须去掉,
            if(deque.peekFirst() == nums[i - k])  deque.removeFirst();
            //如果当前待入栈元素大于队列尾部元素,则将尾部元素弹出  只到当前待入栈元素不大于队尾元素  或者队列为空
             while(!deque.isEmpty() && nums[i] > deque.peekLast())
                  deque.removeLast();
            deque.addLast(nums[i]);//将当前元素入队
            res[j++] = deque.peekFirst();//获取第一个k位置的最大值

        }
         return res;
    }

}

Guess you like

Origin blog.csdn.net/weixin_45618869/article/details/132992938