单调队列 Monotonic Queue / 单调栈 Monotonic Stack
生活随笔
收集整理的這篇文章主要介紹了
单调队列 Monotonic Queue / 单调栈 Monotonic Stack
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
2018-11-16 22:45:48
一、單調(diào)隊(duì)列 Monotone Queue
- 239.?Sliding Window Maximum
問(wèn)題描述:
問(wèn)題求解:
本題是一個(gè)經(jīng)典的可以使用雙端隊(duì)列或者說(shuō)單調(diào)隊(duì)列完成的題目,具體來(lái)說(shuō),就是通過(guò)雙端隊(duì)列將可能的最大值維護(hù)起來(lái)。
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.getFirst() < nums[i]) q.pollFirst();q.addFirst(nums[i]);if (i >= k - 1) {res[i - k + 1] = q.getLast();if (q.getLast() == nums[i - k + 1]) q.pollLast();}}return res;}
二、單調(diào)棧 Monotone Stack
什么是Monotonic Stack?
答:從棧頂?shù)綏5资前凑諉握{(diào)順序排列的。
- 739.?Daily Temperatures
問(wèn)題描述:
問(wèn)題求解:
維護(hù)一個(gè)從棧頂?shù)綏5讍握{(diào)遞增的棧。
從末尾向前遍歷,如果當(dāng)前的數(shù)值比棧頂?shù)臄?shù)值要大的話,那么顯然更小的數(shù)值是不再需要的了,直接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
問(wèn)題描述:
問(wèn)題求解:
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
問(wèn)題描述:
問(wèn)題求解:
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;} }
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/TIMHY/p/9972221.html
總結(jié)
以上是生活随笔為你收集整理的单调队列 Monotonic Queue / 单调栈 Monotonic Stack的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 中文字体练习好看的手写字
- 下一篇: 6.2.2 二叉树的创建