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:
Example 2:
Example 3:
解法1: O(N) Time
参考了discussion的解答, 基本思想是我们从后往前扫描. 用一个stack维护一个递增的序列, stack中的值则是s2的备选. 每当扫描一个新数时,先比较是否比s3小,如果比s3小则说明已找到答案.如果比s3大则更新s3和s2的值.
更新的时候: 把stack中所有比当前值小的数弹出, 每一个弹出的数都是s3的备选.
C++
Java