forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSliding Window Maximum.java
More file actions
58 lines (45 loc) · 1.6 KB
/
Sliding Window Maximum.java
File metadata and controls
58 lines (45 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Solution {
public static int[] maxSlidingWindowDynamic(int[] nums, int k) {
if (nums.length == 0 || nums.length < k) {
return new int[]{};
}
int[] maxLeft = new int[nums.length];
int[] maxRight = new int[nums.length];
maxLeft[0] = nums[0];
maxRight[nums.length-1] = nums[nums.length-1];
for (int i=1; i<nums.length; i++) {
maxLeft[i] = i%k == 0 ? nums[i] : Math.max(nums[i], maxLeft[i-1]);
int j = nums.length - i - 1;
maxRight[j] = j%k == 0 ? nums[j] : Math.max(maxRight[j+1], nums[j]);
}
int[] ans = new int[nums.length - k + 1];
for (int i=0; i<=nums.length-k; i++) {
ans[i] = Math.max(maxRight[i], maxLeft[i + k - 1]);
}
return ans;
}
public static int[] maxSlidingWindow(int[] nums, int k) {
if (nums.length == 0 || nums.length < k) {
return new int[]{};
}
int[] ans = new int[nums.length-k+1];
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
for (int i=0; i<k; i++) {
priorityQueue.add(nums[i]);
}
int j = 0;
for (int i=k; i<nums.length; i++) {
ans[j] = priorityQueue.peek();
priorityQueue.remove(nums[j]);
priorityQueue.add(nums[i]);
j++;
}
ans[j] = priorityQueue.peek();
return ans;
}
}