8000 edit 239 · seshireddy/Leetcode@86b06c1 · GitHub
[go: up one dir, main page]

Skip to content

Commit 86b06c1

Browse files
edit 239
1 parent aa6a4f6 commit 86b06c1

File tree

2 files changed

+19
-28
lines changed

2 files changed

+19
-28
lines changed

src/main/java/com/fishercoder/solutions/_239.java

Lines changed: 16 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import java.util.*;
44

55
/**
6+
* 239. Sliding Window Maximum
7+
*
68
* 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.
79
* You can only see the k numbers in the window. Each time the sliding window moves right by one position.
810
@@ -11,7 +13,7 @@
1113
1214
Window position Max
1315
--------------- -----
14-
[1 3 -1] -3 5 3 6 7 3
16+
[1 3 -1] -3 5 3 6 7 3
1517
1 [3 -1 -3] 5 3 6 7 3
1618
1 3 [-1 -3 5] 3 6 7 5
1719
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)?
3436
public class _239 {
3537

3638
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();
4452
}
4553
}
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-
}
6254
return res;
6355
}
64-
6556
}

src/test/java/com/fishercoder/_239Test.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,9 @@ public static void setup(){
2323

2424
@Before
2525
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[]{};
2929
k = 0;
3030
}
3131

0 commit comments

Comments
 (0)
0