public int[] maxSlidingWindow(int[] a, int k) {
if (a == null || k <= 0) {
return new int[0];
}
int n = a.length;
int[] r = new int[n-k+1];
int ri = 0;
// store index
Deque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < a.length; i++) {
// remove numbers out of range k
while (!q.isEmpty() && q.peek() < i - k + 1) {
q.poll();
}
// remove smaller numbers in k range as they are useless
while (!q.isEmpty() && a[q.peekLast()] < a[i]) {
q.pollLast();
}
// q contains index... r contains content
q.offer(i);
if (i >= k - 1) {
r[ri++] = a[q.peek()];
}
}
return r;
}
public class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null || nums.length == 0) return nums;
int[] result = new int[nums.length - k + 1];
int max = findMax(nums, 0, k - 1);
result[0] = max;
for (int i = 1; i < nums.length - k + 1; i++) {
int current = i + k - 1;
int previous = i - 1;
if (nums[current] >= max) {
max = nums[current];
} else {
if (nums[previous] == max) max = findMax(nums, i, current);
}
result[i] = max;
}
return result;
}
private int findMax(int[] nums, int start, int end) {
int max = Integer.MIN_VALUE;
for (int i = start; i <= end; i++) {
if (nums[i] > max) max = nums[i];
}
return max;
}
}
public class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null || nums.length < 1 || k <= 0) return new int[0];
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(new Comparator<Integer>(){
public int compare (Integer a, Integer b) {
return b - a;
}
});
int n = nums.length;
int[] res = new int[n - k + 1];
for (int i = 0; i < k; i++) {
maxHeap.offer(nums[i]);
}
res[0] = maxHeap.peek();
for (int i = k; i < n; i++) {
maxHeap.remove(nums[i - k]);
maxHeap.offer(nums[i]);
res[i - k + 1] = maxHeap.peek();
}
return res;
}
}