Problem description
Given an array nums, there is a sliding window of size K which are moving from the very left Of the array to the very right. You can only see the k numbers in the window. Each of the sliding window moves right by one position.
For example,
Given nums = [1,3,-1,-3,5,3,6,7]
, and k = 3.
Window position Max--------------- -----[1 3 -1]-3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7
Therefore, return the max sliding window as [3,3,5,5,6,7]
.
Solution Ideas
1. The most intuitive method is to compare each other, the time complexity of O (kn);
2. Another more ingenious approach is to use a two-way queue to record the maximum value of the current window while sliding the window.
The specific approach is
1. When the number of input elements is less than K, enter the queue;
2. Otherwise, compare the elements of the current element and the tail of the queue, and if the element at the end of the queue is smaller than the current element, the team tail element is continuously out of line;
3. Each time the head element of the queue is recorded is the largest element in the sliding window, and it is necessary to determine whether the largest element is the first element of the window, and if so, to remove it.
Program
public class Solution {public int[] Maxslidingwindow (int[] nums, int k) {if (nums = = NULL | | nums.length = 0 | | nums . length < K) {return new int[0];} linkedlist<integer> doublyqueue = new linkedlist<integer> (); int[] Maxs = new Int[nums.length-k + 1];
for (int i = 0; i < Nums.length, i++) {while (!doublyqueue.isempty () && doublyqueue.getlast () < nums[i]) {do Ublyqueue.removelast ();} Doublyqueue.add (Nums[i]); if (I < k-1) {continue;} Maxs[i-k + 1] = Doublyqueue.getfirst (), if (doublyqueue.getfirst () = = Nums[i-k + 1]) {Doublyqueue.removefirst ();}} return maxs;}}
Sliding Window Maximum