456. 132 Pattern

456. 132 Pattern

Given an array of integers a1, a2, a3…an, judge if there exists the 132 pattern. 

132 pattern is ai < ak < aj, in which i < j < k.

 

Solution:

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

 

Find the subsequence s1 < s3 < s2

  1. Search from the end of the array, the current is the s1 candidate, because this is the first place in the array
  2. If the current is smaller than the top number in the stack, push it in; If the current is larger than some of the numbers in the stack, pop the smaller ones, let s3 = the last pop, and push the current in. The stack holds the s2 candidates.
  3. If the current is smaller than the s3, which means it is definitely < all in the stack, which is the s2 candidates, return true.
  4. If the it doesn’t meet the return true condition, return false.

 

 

 1 public class Solution {
 2     public boolean find132pattern(int[] nums) {
 3         int s1, s3 = Integer.MIN_VALUE;
 4         Stack<Integer> stack = new Stack<Integer>();
 5         for(int i = nums.length - 1; i >= 0; i--) {
 6             if(nums[i] < s3) return true;
 7             else {
 8                 while(!stack.isEmpty() && nums[i] > stack.peek()) {
 9                     s3 = stack.pop();
10                 }
11             }
12             stack.push(nums[i]);
13         }
14         return false;
15     }
16 }

 

转载于:https://www.cnblogs.com/CornerCase/p/6268246.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器学习模型机器
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值