leetcode解题: 132 Pattern (456)

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:

1
2
3
4
5
Input: [1, 2, 3, 4]
Output: False
Explanation: There is no 132 pattern in the sequence.

Example 2:

1
2
3
4
5
Input: [3, 1, 4, 2]
Output: True
Explanation: There is a 132 pattern in the sequence: [1, 4, 2].

Example 3:

1
2
3
4
5
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].

解法1: O(N) Time

参考了discussion的解答, 基本思想是我们从后往前扫描. 用一个stack维护一个递增的序列, stack中的值则是s2的备选. 每当扫描一个新数时,先比较是否比s3小,如果比s3小则说明已找到答案.如果比s3大则更新s3和s2的值.
更新的时候: 把stack中所有比当前值小的数弹出, 每一个弹出的数都是s3的备选.
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
bool find132pattern(vector<int>& nums) {
int s3 = INT_MIN;
stack<int> s2;
for (int i = nums.size() - 1; i >= 0; --i) {
if (nums[i] < s3) {
return true;
}
while (!s2.empty() && s2.top() < nums[i]) {
s3 = s2.top(); s2.pop();
}
s2.push(nums[i]);
}
return false;
}
};

Java

1