单调队列 Monotonic Queue / 单调栈 Monotonic Stack
2018-11-16 22:45:48
一、单调队列 Monotone Queue
- 239. Sliding Window Maximum
问题描述:
问题求解:
本题是一个经典的可以使用双端队列或者说单调队列完成的题目,具体来说,就是通过双端队列将可能的最大值维护起来。
public int[] maxSlidingWindow(int[] nums, int k) { if (nums == null || nums.length < k || k == 0) return new int[0]; Deque<Integer> q = new LinkedList<>(); int[] res = new int[nums.length - k + 1]; for (int i = 0; i < nums.length; i++) { while (!q.isEmpty() && q.getLast() < nums[i]) q.pollLast(); q.addLast(nums[i]); if (i >= k - 1) { res[i - k + 1] = q.getFirst(); if (q.getFirst() == nums[i - k + 1]) q.pollFirst(); } } return res; }
二、单调栈 Monotone Stack
什么是Monotonic Stack?
答:从栈顶到栈底是按照单调顺序排列的。
- 739. Daily Temperatures
问题描述:
问题求解:
维护一个从栈顶到栈底单调递增的栈。
从末尾向前遍历,如果当前的数值比栈顶的数值要大的话,那么显然更小的数值是不再需要的了,直接pop即可。
public int[] dailyTemperatures(int[] T) { int[] res = new int[T.length]; Stack<int[]> stack = new Stack<>(); for (int i = T.length - 1; i >= 0; i--) { while (!stack.isEmpty() && stack.peek()[0] <= T[i]) stack.pop(); res[i] = stack.isEmpty() ? 0 : stack.peek()[1] - i; stack.push(new int[]{T[i], i}); } return res; }
- 1019. Next Greater Node In Linked List
问题描述:
问题求解:
public int[] nextLargerNodes(ListNode head) { List<Integer> nums = new ArrayList<>(); for (ListNode cur = head; cur != null; cur = cur.next) { nums.add(cur.val); } int[] res = new int[nums.size()]; Stack<Integer> stack = new Stack<>(); for (int i = nums.size() - 1; i >= 0; i--) { while (!stack.isEmpty() && stack.peek() <= nums.get(i)) stack.pop(); res[i] = stack.isEmpty() ? 0 : stack.peek(); stack.push(nums.get(i)); } return res; }
- 901. Online Stock Span
问题描述:
问题求解:
public class StockSpanner { Stack<int[]> stack; int idx; public StockSpanner() { stack = new Stack<>(); stack.push(new int[]{Integer.MAX_VALUE, -1}); idx = 0; } public int next(int price) { while (stack.peek()[1] <= price) stack.pop(); int res = idx - stack.peek()[1]; stack.push(new int[]{price, idx}); idx++; return res; } }