456 132 Pattern

1 题目

Given a sequence of n integers a1, a2, ..., an, a 132 pattern is a subsequence ai, aj, ak such that i < jk 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.

Note: n will be less than 15,000.

Example 1:

Input: [1, 2, 3, 4]

Output: False

Explanation: There is no 132 pattern in the sequence.

Example 2:

Input: [3, 1, 4, 2]

Output: True

Explanation: There is a 132 pattern in the sequence: [1, 4, 2].

Example 3:

Input: [-1, 3, 2, 0]

Output: True

Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].

2 尝试解

2.1 分析

最初尝试用解决123Pattern的方式,即记录最小值、次小值,如果有次小值大的,就返回True。但是在[1,0,1,-4,-3]上失效了,因为最小值更新为-4后,最大值并没有更新,仍为1,会返回True。即最大值和最小值应该成对更新,或者在找到最大值时,才能更新最小值。

所以尝试采用min[0],min[1]记录当前的最大最小值区间。当遇到更小的时候,先用min[1]保存起来,当遇到比min[1]更大的数后,正式更新min[0]和max。但是在[3,5,0,3,4]上失效,因为区间从[3,5]更新到了[0,3],所以返回False。

最后采用一个向量,把所有的有效区间保存下来。

2.2 代码

class Solution {
public:
    bool find132pattern(vector<int>& nums) {
        int min = INT_MAX;
        int max = INT_MIN;
        vector<pair<int,int>> interval;
        for(auto num : nums){
            for(auto range:interval){
                if(num > range.first && num < range.second) return true;
            }
            if(num < min ){
                if(min < max) interval.emplace_back(make_pair(min,max));
                min = num;
                max = INT_MIN;
            }
            else if(num > max) max = num;
            else if(num > min && num < max)return true;
        }
        return false;
    }
};

3 标准解

class Solution {
public:
    bool find132pattern(vector<int>& nums) {
        int s3 = INT_MIN;
        stack<int> st;
        for( int i = nums.size()-1; i >= 0; i -- ){
            if( nums[i] < s3 ) return true;
            else while( !st.empty() && nums[i] > st.top() ){ 
              s3 = st.top(); st.pop(); 
            }
            st.push(nums[i]);
        }
        return false;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值