日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

单调队列 Monotonic Queue / 单调栈 Monotonic Stack

發(fā)布時(shí)間:2024/4/15 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 单调队列 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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。