Title Link: https://leetcode.com/problems/sliding-window-maximum/
Topic:
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].
Note:
You may assume k are always valid, Ie:1≤k≤input array's size for non-empty array.
Follow up:
Could solve it in linear time?
Ideas:
It was hard, indeed. Want to do O (N) solution did not think out, looked at the online thinking, the results found. Also O (n*k) ... The Pit-daddy?
Algorithm:
Public int[]Maxslidingwindow(int[] Nums,intK) {if(k==0)return New int[0];intRes[] =New int[Nums.length-k +1]; Linkedlist<integer> IDXS =NewLinkedlist<integer> (); for(inti =0; i < nums.length; i++) { while(!idxs.isempty () && nums[i] >=nums[idxs.getlast ()) {//Delete all elements within the window that are less than the element I will enterIdxs.removelast ();//Because I is the newest element in the window, the element smaller than it certainly kicks out of the window sooner than it} idxs.addlast (i);if(I-idxs.getfirst () +1> k) {Idxs.removefirst (); }if(i +1>= k) res[i-k+1] = Nums[idxs.getfirst ()]; }returnRes }
"Leetcode" Sliding window Maximum