Jianzhi offer—59. The maximum value of sliding window—analysis and code (Java)

Sword refers to offer-59. Maximum sliding window-analysis and code [Java]

1. Title

Given an array and the size of the sliding window, find the maximum value of all sliding windows.
For example, if the input array {2,3,4,2,6,2,5,1} and the sliding window size 3, then there are 6 sliding windows in total, and their maximum values ​​are {4,4,6, 6,6,5};
there are 6 sliding windows for the array {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}, {2,3,4,2,6,[2,5, 1]}.

Two, analysis and code

1. Auxiliary queue

(1) Thinking

Design an auxiliary queue to store the coordinates of the number that may become the maximum value in the current window. When the window is sliding:
1) If the new number is greater than or equal to the number corresponding to the tail coordinates of the current queue, pop the tail numbers one by one until the new number is less than the tail number or the queue is empty;
2) When the queue is empty or the new number is less than the current queue tail When the coordinate corresponds to the number, the number may become the maximum value in the window, and push its coordinate into the queue;
3) Determine whether the coordinate of the head of the queue is still within the window range, if it is out of range, pop the head number.
At this time, the number corresponding to the coordinates of the head of the queue is the maximum value in the sliding window.

(2) Code

import java.util.*;
public class Solution {
    
    
    public ArrayList<Integer> maxInWindows(int [] num, int size)
    {
    
    
        ArrayList<Integer> ans = new ArrayList<>();
        if (num.length == 0 || size == 0)
            return ans;
        
        ArrayDeque<Integer> deq = new ArrayDeque<>();
        for (int i = 0; i < num.length; i++) {
    
    
            while (!deq.isEmpty() && num[deq.peekLast()] <= num[i])
                deq.pollLast();
            deq.add(i);
            if (deq.peekFirst() + size == i)
                deq.pollFirst();
            if (i >= size - 1)
                ans.add(num[deq.peekFirst()]);
        }
        
        return ans;
    }
}

(3) Results

Running time: 26ms, occupied memory: 9512k.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/112127713