[LeetCode]456.132模式

    xiaoxiao2022-07-05  149

    题目描述:给定一个整数序列:a1, a2, …, an,一个132模式的子序列 ai, aj, ak 被定义为:当 i < j < k 时,ai < ak < aj。设计一个算法,当给定有 n 个数字的序列时,验证这个序列中是否含有132模式的子序列。 题目链接:456.132模式

    思路参考评论区: last用来存储132中的2,在操作过程中显然递增。 q是栈,用来存储132中的3,且从栈底到栈顶不上升。

    class Solution { public: bool find132pattern(vector<int>& nums) { int n=nums.size(); int last=-2e9; stack<int> q; for (int i=n-1;i>=0;i--){ if (nums[i]<last) return true; while (!q.empty() && q.top()<nums[i]){ last=q.top(); q.pop(); } q.push(nums[i]); } return false; } };
    最新回复(0)