File tree Expand file tree Collapse file tree 1 file changed +15
-17
lines changed Expand file tree Collapse file tree 1 file changed +15
-17
lines changed Original file line number Diff line number Diff line change 4
4
* @return {number[] }
5
5
*/
6
6
const maxSlidingWindow = function ( nums , k ) {
7
- let n = nums . length
8
- if ( n === 0 ) {
9
- return nums
10
- }
11
- let result = [ ]
12
-
13
- let dq = [ ]
14
- for ( let i = 0 ; i < n ; i ++ ) {
15
- if ( dq . length && dq [ 0 ] < i - k + 1 ) {
16
- dq . shift ( )
7
+ const n = nums . length
8
+ const stk = [ ]
9
+ const res = [ ]
10
+
11
+ for ( let i = 0 ; i < n ; i ++ ) {
12
+ while ( stk . length && stk [ 0 ] < i - k + 1 ) {
13
+ stk . shift ( )
17
14
}
18
- while ( dq . length && nums [ i ] >= nums [ dq [ dq . length - 1 ] ] ) {
19
- dq . pop ( )
15
+ while ( stk . length && nums [ stk [ stk . length - 1 ] ] <= nums [ i ] ) {
16
+ stk . pop ( )
20
17
}
21
- dq . push ( i )
22
- if ( i - k + 1 >= 0 ) {
23
- result [ i - k + 1 ] = nums [ dq [ 0 ] ]
18
+ stk . push ( i )
19
+ if ( i >= k - 1 ) {
20
+ res . push ( nums [ stk [ 0 ] ] )
24
21
}
25
22
}
26
- return result
27
- }
23
+
24
+ return res
25
+ } ;
You can’t perform that action at this time.
0 commit comments