Problems:
239. Sliding Window Maximum:
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null || k == 0) {
return new int[0];
}
int[] maxSlidingWindow = new int[nums.length - k + 1];
int maxSlidingWindowPos = 0;
Deque<Integer> potential = new ArrayDeque<>();
for (int i = 0; i < nums.length; i++) {
while (!potential.isEmpty() && potential.peekFirst() < i - k + 1) {
potential.pollFirst();
}
while (!potential.isEmpty() && nums[potential.peekLast()] < nums[i]) {
potential.pollLast();
}
potential.offer(i);
if (i - k + 1 >= 0) {
maxSlidingWindow[maxSlidingWindowPos++] = nums[potential.peekFirst()];
}
}
return maxSlidingWindow;
}
}
沒有留言:
張貼留言