|
1 |
| -import java.util.ArrayDeque; |
2 |
| -import java.util.Deque; |
| 1 | +import java.util.Stack; |
3 | 2 |
|
4 | 3 | public class MaximumsOfSlidingWindow {
|
5 | 4 | public int[] maximumsOfSlidingWindow(int[] nums, int k) {
|
6 | 5 | int[] res = new int[nums.length - k + 1];
|
7 |
| - Deque<int[]> dq = new ArrayDeque<>(); |
| 6 | + Stack<int[]> dq = new Stack<>(); |
8 | 7 | int left, right;
|
9 | 8 | left = right = 0;
|
10 | 9 | while (right < nums.length) {
|
11 | 10 | // 1) Ensure the values of the deque maintain a monotonic decreasing order
|
12 | 11 | // by removing candidates <= the current candidate.
|
13 |
| - while (!dq.isEmpty() && dq.peekLast()[0] <= nums[right]) { |
14 |
| - dq.pollLast(); |
| 12 | + while (!dq.isEmpty() && dq.peek()[0] <= nums[right]) { |
| 13 | + dq.pop(); |
15 | 14 | }
|
16 | 15 | // 2) Add the current candidate.
|
17 |
| - dq.offerLast(new int[]{nums[right], right}); |
| 16 | + dq.push(new int[]{nums[right], right}); |
18 | 17 | // If the window is of length 'k', record the maximum of the window.
|
19 | 18 | if (right - left + 1 == k) {
|
20 | 19 | // 3) Remove values whose indexes occur outside the window.
|
21 |
| - if (!dq.isEmpty() && dq.peekFirst()[1] < left) { |
22 |
| - dq.pollFirst(); |
| 20 | + if (!dq.isEmpty() && dq.firstElement()[1] < left) { |
| 21 | + dq.remove(0); |
23 | 22 | }
|
24 | 23 | // The maximum value of this window is the leftmost value in the
|
25 | 24 | // deque.
|
26 |
| - res[left] = dq.peekFirst()[0]; |
| 25 | + res[left] = dq.firstElement()[0]; |
27 | 26 | // Slide the window by advancing both 'left' and 'right'. The right
|
28 | 27 | // pointer always gets advanced so we just need to advance 'left'.
|
29 | 28 | left++;
|
|
0 commit comments