Topic
Given an array and the size of the sliding window, find the maximum value of the values in all the sliding windows.
For example, if the input array {2,3,4,2,6,2,5,1} and the size of the sliding window 3, there are altogether 6 sliding windows, their maximum value is {4,4,6,6,6,5}, the sliding window for the array {2,3,4,2,6,2,5,1} has the following 6:
{[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]}.
Solving
Method One: Violence
Complexity of Time: O(nk)
Import Java.util.*;public class Solution {public arraylist<integer> maxinwindows (int[] num,int size{arraylist<integer> result = new arraylist<integer> ();intlen = num.length;if(size<=0||size> Len)returnResult for(intI=0; i<len;i++) {int Max= Integer.min_value; for(intk=0; K+i < Len && k<size; k++) {Max=Max>NUM[I+K]?Max: Num[i+k]; } result.add (Max);if(i+size==len) Break; }returnResult }}
Method Two: Using the queue
The queue holds the subscript of the larger element in the sliding window
ImportJava.util.ArrayList;Importjava.util.*; Public class solution { PublicArraylist<integer>maxinwindows(int[] num,intSize) {arraylist<integer> result =NewArraylist<> ();if(num = =NULL) {returnResult }if(Num.length < Size | | Size <1) {returnResult } linkedlist<integer> Indexdeque =NewLinkedlist<> (); for(inti =0; i < size; i++) { while(!indexdeque.isempty () && num[i] >= num[indexdeque.getlast ()]) {indexdeque.removelast (); } indexdeque.addlast (i); } for(inti = size; i < num.length; i++) {Result.add (Num[indexdeque.getfirst ())); while(!indexdeque.isempty () && num[i] >= num[indexdeque.getlast ()]) {indexdeque.removelast (); }if(!indexdeque.isempty () && Indexdeque.getfirst () <= (i-size)) {Indexdeque.removefirst (); } indexdeque.addlast (i); } result.add (Num[indexdeque.getfirst ()));returnResult }}
Maximum number of sliding windows