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]
.
Test instructions
Given an array sequence, and a fixed-size window K, scan the array with k from front to back, returning the maximum value for each state of the window.
Ideas:
Use the double-ended queue deque as a sliding window to ensure that the maximum value is always at the top of the team in each state. For example [1,3,-1,-3,5,3,6,7], then the state of Deque is [1], [3] (the first 2 steps, fill the sliding window), (starting from the third step formally) [3,-1], [3,-1,-3], [5], [5,3], [6], [7], You can see that the first element of each queue is the maximum value of the current sliding window, and the procedure can refer to the code with comments. Time complexity O (n).
C++:
classSolution { Public: Vector<int> Maxslidingwindow (vector<int>& Nums,intk) {vector<int>ret; if(nums.size () = =0) returnret; //A double-ended queue that stores the subscript of an element, not the value of an elementdeque<int>Slidewindow; for(inti =0; I < K; i++) { //if the number to be queued is larger than the number in front of it, the number before it is removed from the back until the number in front of it is larger than it or the queue is empty while(!slidewindow.empty () && Nums[i] >=Nums[slidewindow.back ()]) {Slidewindow.pop_back (); } //adding new elements to the queueSlidewindow.push_back (i); } for(inti = k; I < nums.size (); i++) { //the first element of the team is the maximum value of the current windowRet.push_back (Nums[slidewindow.front ()); //if the number to be queued is larger than the number in front of it, the number before it is removed from the back until the number in front of it is larger than it or the queue is empty while(!slidewindow.empty () && Nums[i] >=Nums[slidewindow.back ()]) {Slidewindow.pop_back (); } //if the element of the current team header is no longer inside the window, remove it from the front of the queue if(!slidewindow.empty () && slidewindow.front () <= I-k) Slidewindow.pop_front (); //adding new elements to the queueSlidewindow.push_back (i); } //don't forget the result of the last window--Ret.push_back (Nums[slidewindow.front ()); returnret; }};
"Leetcode 239" Sliding window Maximum