很不擅长的一部份内容,值得总结一下
monotonic queue的应用有
1.求previous less element(PLE), next greater element(NLE), previous greater element(PGE), next greater element(NGE)。以求PGE为例,有两种方式:数组
public int[] PGE(int[] nums) { int[] res = new int[nums.length]; Arrays.fill(res, nums.length); // nums.length表示不存在NGE Stack<Integer> s = new Stack<>(); for (int i = 0; i < nums.length; i ++) { while (!s.isEmpty() && nums[i] > nums[s.peek()]) res[s.pop()] = i; s.push(i); } return res; }
public int[] PGE(int[] nums) { int[] res = new int[nums.length]; Arrays.fill(res, nums.length); Stack<Integer> s = new Stack<>(); for (int i = nums.length-1; i >= 0; i --) { while (!s.isEmpty() && nums[s.peek()] <= nums[i]) s.pop(); if (!s.isEmpty()) res[i] = s.peek(); s.push(i); } return res; }
以上都是严格大于的状况,若是是大于等于则解法一nums[i] >= nums[s.peek(),解法二nums[s.peek()] < nums[i]
用monotonic queue解决问题时须要考虑使用decreasing queue仍是increasing queue,想清楚这个问题再实现代码。app
有的时候咱们须要同时求PLE和NLE,能够用两个数组分别存储每一个位置对应的PLE和NLE,还能够仅用一个monotonic queue。要求PLE和NLE时维护一个increasing stack,求PGE和NGE时维护一个decreasing stack,详见下面两题
42. Trapping Rain Water
84. Largest Rectangle in Histogram
好处是不用担忧左右两边重复计算的问题,但有时要考虑最后是否须要再push一个bar来处理最后一个数
码。
ps: 维护单调增区间:从尾部去掉比当前大的;维护单调减区间:从尾部去掉比当前小的less