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.
 public class Solution {
public boolean find132pattern(int[] nums) {
int s1, s3 = Integer.MIN_VALUE;
Stack<Integer> stack = new Stack<Integer>();
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;
}
}

最新文章

  1. 弱省互测#1 t3
  2. JavaScript实现简单的双向绑定
  3. Xcode 6制作动态及静态Framework和各种坑
  4. 【T_SQL】 基础
  5. iOS - OC NSNumber 数字
  6. C 基于UDP实现一个简易的聊天室
  7. linux笔记_20150825_linux下的软件工具唠叨下
  8. Metasploit介绍
  9. matlab制造一个64*64的仿真数据
  10. 编译安装php时提示Cannot find MySQL header files的解决方法
  11. Python函数小结(1)--参数类型(*, ** 的区别), 闭包
  12. SQLServer 2008 :error 40 出现连接错误
  13. Node Node
  14. iOS ,呼叫捕获抛出勉未知方法的障碍
  15. linux查询进程号,出现两个进程
  16. [转载]python 详解re模块
  17. Promise同时进入catch和then——踩坑
  18. 微信小程序UI组件、开发框架、实用库...
  19. 如何将html特殊字符编码转换成特殊字符_html十进制编码字符转回来
  20. hadoop 集群 master datanode 没有启动

热门文章

  1. [Oracle] 参数修改小结
  2. web前端之 CSS引入第三方插件
  3. (转)25个增强iOS应用程序性能的提示和技巧--初级篇
  4. [Git] set-upstream
  5. 飘逸的python - hack输出流便于调试
  6. jsp文件上传
  7. Android--------Java接口回调
  8. WebBrowser如何获取提交的数据
  9. 写一个Windows上的守护进程(8)获取进程路径
  10. vs2010中出现:程序管理器匹配不正确错误