File tree Expand file tree Collapse file tree 3 files changed +59
-0
lines changed Expand file tree Collapse file tree 3 files changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ public class Solution {
2
+
3
+ static class SlidingMaxQueue {
4
+
5
+ int [] nums ;
6
+ int k ;
7
+
8
+ LinkedList <Integer > queue = new LinkedList <>();
9
+
10
+ SlidingMaxQueue (int [] nums , int k ){
11
+ this .nums = nums ;
12
+ this .k = k ;
13
+ }
14
+
15
+ int max (){
16
+ return nums [queue .peekFirst ()];
17
+ }
18
+
19
+ void add (int i ){
20
+
21
+ if (i >= nums .length ) return ;
22
+
23
+ // remove invalid index
24
+ while (!queue .isEmpty () && queue .peekFirst () <= i - k ){
25
+ queue .pollFirst ();
26
+ }
27
+
28
+ // remove nums < current;
29
+ while (!queue .isEmpty () && nums [queue .peekLast ()] < nums [i ]){
30
+ queue .pollLast ();
31
+ }
32
+
33
+ queue .add (i );
34
+ }
35
+ }
36
+
37
+ public int [] maxSlidingWindow (int [] nums , int k ) {
38
+
39
+ int [] T = new int [Math .min (nums .length - k + 1 , nums .length )];
40
+
41
+ SlidingMaxQueue Q = new SlidingMaxQueue (nums , k );
42
+
43
+ Q .add (0 );
44
+
45
+ for (int i = 1 ; i <= nums .length ; i ++){
46
+ T [Math .max (i - k , 0 )] = Q .max ();
47
+ Q .add (i );
48
+ }
49
+
50
+ return T ;
51
+ }
52
+ }
Original file line number Diff line number Diff line change
1
+ ---
2
+ layout : solution
3
+ title : Sliding Window Maximum
4
+ date : 2015-07-26 16:53:20+08:00
5
+ leetcode_id : 239
6
+ ---
7
+ {% include_relative README.md %}
You can’t perform that action at this time.
0 commit comments