File tree Expand file tree Collapse file tree 2 files changed +19
-28
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +19
-28
lines changed Original file line number Diff line number Diff line change 3
3
import java .util .*;
4
4
5
5
/**
6
+ * 239. Sliding Window Maximum
7
+ *
6
8
* Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right.
7
9
* You can only see the k numbers in the window. Each time the sliding window moves right by one position.
8
10
11
13
12
14
Window position Max
13
15
--------------- -----
14
- [1 3 -1] -3 5 3 6 7 3
16
+ [1 3 -1] -3 5 3 6 7 3
15
17
1 [3 -1 -3] 5 3 6 7 3
16
18
1 3 [-1 -3 5] 3 6 7 5
17
19
1 3 -1 [-3 5 3] 6 7 5
@@ -34,32 +36,21 @@ How about using a data structure such as deque (double-ended queue)?
34
36
public class _239 {
35
37
36
38
public int [] maxSlidingWindow (int [] nums , int k ) {
37
- if (nums == null || nums .length == 0 || k == 0 ) return new int [0 ];
38
- Queue <Integer > heap = new PriorityQueue <Integer >(new Comparator <Integer >(){
39
- @ Override
40
- public int compare (Integer o1 , Integer o2 ) {
41
- if (o1 > o2 ) return -1 ;
42
- else if (o1 < o2 ) return 1 ;
43
- else return 0 ;
39
+ if (nums == null || nums .length == 0 || k == 0 ) return new int [0 ];
40
+ PriorityQueue <Integer > heap = new PriorityQueue <>((a , b ) -> b - a );
41
+ int [] res = new int [nums .length - k + 1 ];
42
+ for (int i = 0 ; i < nums .length ; i ++) {
43
+ if (i < k ) {
44
+ heap .offer (nums [i ]);
45
+ if (i == k - 1 ) {
46
+ res [0 ] = heap .peek ();
47
+ }
48
+ } else {
49
+ heap .remove (nums [i - k ]);
50
+ heap .offer (nums [i ]);
51
+ res [i - k + 1 ] = heap .peek ();
44
52
}
45
53
}
46
- );
47
- int i = 0 ;
48
- for (; i < k ; i ++){
49
- heap .offer (nums [i ]);
50
- }
51
- List <Integer > list = new ArrayList <Integer >();
52
- list .add (heap .peek ());
53
- for (; i < nums .length ; i ++){
54
- heap .remove (nums [i -k ]);
55
- heap .offer (nums [i ]);
56
- list .add (heap .peek ());
57
- }
58
- int [] res = new int [list .size ()];
59
- for (int j = 0 ; j < list .size (); j ++){
60
- res [j ] = list .get (j );
61
- }
62
54
return res ;
63
55
}
64
-
65
56
}
Original file line number Diff line number Diff line change @@ -23,9 +23,9 @@ public static void setup(){
23
23
24
24
@ Before
25
25
public void setupForEachTest (){
26
- expected = new int [1000 ] ;
27
- actual = new int [1000 ] ;
28
- nums = new int [1000 ] ;
26
+ expected = new int []{} ;
27
+ actual = new int []{} ;
28
+ nums = new int []{} ;
29
29
k = 0 ;
30
30
}
31
31
You can’t perform that action at this time.
0 commit comments