LeetCode 456. 132 Pattern

来源:互联网 发布:c程序员面试题库 编辑:程序博客网 时间:2024/05/17 06:01

456. 132 Pattern

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

Analysis
这道题的意思是问所给整数串中是否存在132形式的整数串,即三个数字中,第二个最大,第三个次大,第一个最小。
我的做法是从最后开始遍历所给整数串。
不从最开始遍历的原因是因为第三个是次大的数字,相对来说会容易一些。
我的做法是采用一个temp来记录当前整数以及其后面的整数串中的次大数字。
一旦在当前整数之前找到比temp小的数,就证明存在132形式。

Code

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