Double-ended queue to solve the window sliding problem

package queue;

import java.util.ArrayDeque;
import java.util.Deque;

class SildeWindow{

public int[] getMax(Integer[] data,int window ) {
Deque<Integer> deque=new ArrayDeque<Integer>();
int[] res=new int[data.length-window+1];/ /res record the maximum value of the window
int j=0; //the subscript of res
//traverse the array
for(int i=0;i<data.length;i++) {
//the first window is enqueued w-1 Number
if(i<window-1){
deque.push(i);
}else {
//The last data of the window (not yet in the queue), larger than the element at the end of the queue (first end), let the end of the queue go out Team
while(!deque.isEmpty()&&data[i]>data[deque.peekFirst()]) {
deque.pollLast();
}
//Determine whether the queue head (last end) element is expired (that is, outside the window), If it expires, dequeue
if(!deque.isEmpty()&&deque.peekLast()<i+1-window) {
deque.pollLast();
}
//After the above operation, let the last data of the window enter the queue
deque.push( i);
//At this time, the last of the queue is the maximum value of the window
res[j++]=data[deque.peekLast()];
}
}
return res;
}
}
public class MoveWindow {

public static void main(String[] args) {
Integer[] data=new Integer[] {4,3,5,4,3,3,6,7};
int window=3;
SildeWindow sw=new SildeWindow();
int[] res=sw.getMax(data,window);
for(int i:res) {
System.out.println(i);
}
}

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324816949&siteId=291194637