Skip to content

Commit f5c89a0

Browse files
refactor 239
1 parent 97357b8 commit f5c89a0

File tree

2 files changed

+21
-22
lines changed

2 files changed

+21
-22
lines changed

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

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -35,24 +35,26 @@ How about using a data structure such as deque (double-ended queue)?
3535
*/
3636
public class _239 {
3737

38-
public int[] maxSlidingWindow(int[] nums, int k) {
39-
if (nums == null || nums.length == 0 || k == 0) {
40-
return new int[0];
41-
}
42-
PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> b - a);
43-
int[] res = new int[nums.length - k + 1];
44-
for (int i = 0; i < nums.length; i++) {
45-
if (i < k) {
46-
heap.offer(nums[i]);
47-
if (i == k - 1) {
48-
res[0] = heap.peek();
38+
public static class Solution1 {
39+
public int[] maxSlidingWindow(int[] nums, int k) {
40+
if (nums == null || nums.length == 0 || k == 0) {
41+
return new int[0];
42+
}
43+
PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> b - a);
44+
int[] res = new int[nums.length - k + 1];
45+
for (int i = 0; i < nums.length; i++) {
46+
if (i < k) {
47+
heap.offer(nums[i]);
48+
if (i == k - 1) {
49+
res[0] = heap.peek();
50+
}
51+
} else {
52+
heap.remove(nums[i - k]);
53+
heap.offer(nums[i]);
54+
res[i - k + 1] = heap.peek();
4955
}
50-
} else {
51-
heap.remove(nums[i - k]);
52-
heap.offer(nums[i]);
53-
res[i - k + 1] = heap.peek();
5456
}
57+
return res;
5558
}
56-
return res;
5759
}
5860
}

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

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,16 @@
66
import org.junit.BeforeClass;
77
import org.junit.Test;
88

9-
/**
10-
* Created by fishercoder on 1/10/17.
11-
*/
129
public class _239Test {
13-
private static _239 test;
10+
private static _239.Solution1 solution1;
1411
private static int[] expected;
1512
private static int[] actual;
1613
private static int[] nums;
1714
private static int k;
1815

1916
@BeforeClass
2017
public static void setup() {
21-
test = new _239();
18+
solution1 = new _239.Solution1();
2219
}
2320

2421
@Before
@@ -35,7 +32,7 @@ public void test1() {
3532
nums = new int[]{1, 3, -1, -3, 5, 3, 6, 7};
3633
k = 3;
3734
expected = new int[]{3, 3, 5, 5, 6, 7};
38-
actual = test.maxSlidingWindow(nums, k);
35+
actual = solution1.maxSlidingWindow(nums, k);
3936
Assert.assertArrayEquals(expected, actual);
4037

4138
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy