132 Pattern

问题描述:Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj. Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.

n will be less than 20,000.

使用栈的方法解决。这里需要一个栈和一个变量flag,用来指示第三个元素(即132中的2)。这样只要保证栈中的元素都大于flag,同时新来的数字小于flag,那么则符合要求,如果新来的元素大于flag,那么将栈顶元素赋值flag,将新来的该元素压入栈。保证栈内元素都是大于flag的。c++代码如下:

class Solution {
public:
    /**
     * @param nums a list of n integers
     * @return true if there is a 132 pattern or false
     */
    bool find132pattern(vector<int>& nums) {
        // Write your code here
        int length = nums.size();//数组的大小
        int flag = INT_MIN;
        stack<int> stac;
        for(int i = length-1;i>=0;--i){
            if(nums[i]<flag){
                return true;
            }
            else{
                while(!stac.empty() && nums[i]>stac.top()){
                    flag = stac.top();
                    stac.pop();
                }
            }
            stac.push(nums[i]);
        }
        return false;
    }
};


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值