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

https://discuss.leetcode.com/topic/67881/single-pass-c-o-n-space-and-time-solution-8-lines-with-detailed-explanation

Solution:Stack

思路:
Time Complexity: O(N) Space Complexity: O(N)

Solution Code:

// 定义顺序:s1, s2, s3
// 大小顺序:s1 < s3 < s2
class Solution {
    public boolean find132pattern(int[] nums) {
        int s3 = Integer.MIN_VALUE;
        Deque<Integer> stack = new ArrayDeque<>();
        for(int i = nums.length - 1; i >= 0; i--) {
            if(nums[i] < s3) return true;
            else {
                // 单调递减栈
                while(!stack.isEmpty() && nums[i] > stack.peek()) {
                    s3 = stack.pop();
                }
                stack.push(nums[i]);
            }
        }
        return false;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Given a sequence of n integers a1, a2, ..., an, a 132 pat...
    Jeanz阅读 562评论 0 0
  • 关于爱情,我从没想过,虽然看到身边的朋友成双入对,有的已经开始组建起自己的家庭了,而我对于爱情这个字眼,从不想过分...
    juliexx阅读 406评论 0 3
  • 芳草绵绵碧连天 白云悠悠独自闲 纵马高歌托鸿雁 归来煮酒竟无言 风平浪静空寂寥 波涛如怒吓九霄 茫茫无际随风啸 一...
    星尘梦羽阅读 218评论 0 4
  • 住在这个城市里的人,之所以承载着越来远大的压力和束缚,很有可能是我们想拥有的东西越来越多,之所以想,是因为我们以为...
    兮秒阅读 3,289评论 27 66
  • 作业一:累加求和 作业二:累加求和(二) 作业三:累加求和(三) 作业四:限定输出 作业五:限定输出(二) 作业六...
    qzuser_46e9阅读 246评论 0 0