leetcode 456. 132 Pattern

本文介绍了一种高效算法来检测数组中是否存在132模式,即子序列ai, aj, ak满足i < j < k且ai < ak < aj。通过两种方法实现:使用前缀最小值数组结合有序集合的方法,以及利用单调栈优化复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

456. 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.

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].

题意:判断一个数组num中是否存在132顺序的三个数,注意2比1大哦。

思路1:

用一个数组mi记录前缀最小值,从后往前遍历,当前为i,用一个set记录i之后出现(已经遍历过)的数,则如果在set中找到在(mi[i-1],num[i])之间的数就存在。复杂度O(n*lgn)

代码:

class Solution_456 {
public:
    bool find132pattern(vector<int>& nums) {
        int n=nums.size();
        if(n<=2) return false;
        vector<int>mi(n);
        mi[0]=nums[0];
        for (int i = 1; i <n ; ++i) {
            mi[i]=min(mi[i-1],nums[i]);
        }
        set<int>ri;
        set<int>::iterator it;
        ri.insert(nums[n-1]);
        for (int i = n-2; i >0 ; --i) {
            if(nums[i]>mi[i-1]) {
                it=ri.upper_bound(mi[i-1]);
                if(it!=ri.end()&&*it<nums[i]) return true;
            }
            ri.insert(nums[i]);
        }
        return false;
    }
};


思路2:来源于点击打开链接

从后往前遍历,用一个单调递增的栈(栈顶到栈底递增)维护32,2要尽可能大,如果当前数小于2,那么就找到了,否则更新栈。比当前数小的出栈更新2,然后将当前数入栈,复杂度O(n)

代码:

class Solution_456_On {
public:
    bool find132pattern(vector<int>& nums) {
        int n=nums.size();
        if(n<=2) return false;
        int two=INT32_MIN;
        stack<int>s;
        for (int i = n-1; i >=0 ; --i) {
            if(nums[i]<two) return true;
            while(!s.empty()&&nums[i]>s.top()){
                two=s.top();
                s.pop();
            }
            if(s.empty()||s.top()>nums[i]) s.push(nums[i]);
        }
        return false;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值