Queue
Array
Sliding Window
Monotonic Queue
Heap (Priority Queue)
Description
You are given an array of integers nums
, there is a sliding window of size k
which is moving from the very left of the array to the very right. You can only see the k
numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window .
Example 1:
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
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
Example 2:
Input: nums = [1], k = 1
Output: [1]
Constraints:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
1 <= k <= nums.length
Solutions
Solution 1
Python3 Java C++ Go Rust JavaScript C#
class Solution :
def maxSlidingWindow ( self , nums : List [ int ], k : int ) -> List [ int ]:
q = [( - v , i ) for i , v in enumerate ( nums [: k - 1 ])]
heapify ( q )
ans = []
for i in range ( k - 1 , len ( nums )):
heappush ( q , ( - nums [ i ], i ))
while q [ 0 ][ 1 ] <= i - k :
heappop ( q )
ans . append ( - q [ 0 ][ 0 ])
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 class Solution {
public int [] maxSlidingWindow ( int [] nums , int k ) {
PriorityQueue < int []> q
= new PriorityQueue <> (( a , b ) -> a [ 0 ] == b [ 0 ] ? a [ 1 ] - b [ 1 ] : b [ 0 ] - a [ 0 ] );
int n = nums . length ;
for ( int i = 0 ; i < k - 1 ; ++ i ) {
q . offer ( new int [] { nums [ i ] , i });
}
int [] ans = new int [ n - k + 1 ] ;
for ( int i = k - 1 , j = 0 ; i < n ; ++ i ) {
q . offer ( new int [] { nums [ i ] , i });
while ( q . peek () [ 1 ] <= i - k ) {
q . poll ();
}
ans [ j ++] = q . peek () [ 0 ] ;
}
return ans ;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 class Solution {
public :
vector < int > maxSlidingWindow ( vector < int >& nums , int k ) {
priority_queue < pair < int , int >> q ;
int n = nums . size ();
for ( int i = 0 ; i < k - 1 ; ++ i ) {
q . push ({ nums [ i ], - i });
}
vector < int > ans ;
for ( int i = k - 1 ; i < n ; ++ i ) {
q . push ({ nums [ i ], - i });
while ( - q . top (). second <= i - k ) {
q . pop ();
}
ans . emplace_back ( q . top (). first );
}
return ans ;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 func maxSlidingWindow ( nums [] int , k int ) ( ans [] int ) {
q := hp {}
for i , v := range nums [: k - 1 ] {
heap . Push ( & q , pair { v , i })
}
for i := k - 1 ; i < len ( nums ); i ++ {
heap . Push ( & q , pair { nums [ i ], i })
for q [ 0 ]. i <= i - k {
heap . Pop ( & q )
}
ans = append ( ans , q [ 0 ]. v )
}
return
}
type pair struct { v , i int }
type hp [] pair
func ( h hp ) Len () int { return len ( h ) }
func ( h hp ) Less ( i ,