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 }

 

posted @ 2017-01-10 09:53  CornerCase  阅读(133)  评论(0)    收藏  举报