Leetcode: monotonic queue總結

很不擅長的一部份內容,值得總結一下
monotonic queue的應用有
1.求previous less element(PLE), next greater element(NLE), previous greater element(PGE), next greater element(NGE)。以求PGE爲例,有兩種方式:數組

  1. 從前日後掃,維護一個decreasing monotonic queue
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;
}
  1. 從後往前掃,維護一個decreasing monotonic queue
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

相關文章
相關標籤/搜索