單調(diào)棧 03

單調(diào)棧 03


https://leetcode-cn.com/problems/132-pattern/

單調(diào)棧

  • 需要一個 preMin[n] 來記錄 0 ~ i 區(qū)間內(nèi)最小的數(shù),即 132模式的 “1”
  • 需要一個棧 stack 從后向前遍歷,去找 “3”
  • 至于那個 “2” 就是在從后向前遍歷的過程中,num[i] 充當(dāng)?shù)慕巧?。找到直接返回?/li>
import java.util.*;

public class Solution {

    public boolean find132pattern(int[] nums) {
        int n = nums.length;
        int[] preMin = new int[n];  // 0 ~ i the smallest num
        preMin[0] = nums[0];
        for (int i = 1; i < n; i++)
            preMin[i] = Math.min(preMin[i - 1], nums[i]);
        // the stack store num bigger than preMin[i] and smaller than num[i]
        Deque<Integer> stack = new LinkedList<Integer>();
        for (int i = n - 1; i >= 0; i--) { // from tail to head traversal update stack
            if (nums[i] > preMin[i]) {
                // peek num smaller than all front of num is illicit
                while (!stack.isEmpty() && stack.peek() <= preMin[i])
                    stack.pop();
                // judge whether find 132 pattern
                if (!stack.isEmpty() && stack.peek() < nums[i]) // 3(peek) < 2(num[i])
                    return true;
                stack.push(nums[i]);    // not find, push the num that smaller than preMin[i] into stack
            }
        }
        return false;
    }

}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容