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

题目解读:

就是在数组中看看有没有132这种模式的序列。也就是说 i < j < k && a[i] < a[k]< a[j] 。这样应该解释清楚了吧!

嗯~,提前申明:这是一篇关于答案的解释说明。的确很高超,需要改变习惯,不一定非要从数组的头开始遍历。很厉害的解决方案!
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
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;   //s3 存了大值后面的最后一个数字,那么这里就会比较前后两个数值的关系
            else while( !st.empty() && nums[i] > st.top() ){ 
                s3 = st.top(); 
                st.pop(); 
            }  //大的值会把栈压空!!
            st.push(nums[i]);
        }
        return false;
    }
};
原文地址:https://www.cnblogs.com/Tattoo-Welkin/p/10335314.html