LeetCode 456. 132 Pattern

原题链接在这里:https://leetcode.com/problems/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].

题解:

We want to find out s1 < s3 < s2, actually we want to find out if there is a third value, s3 existing.

We could use stack to store increasing value from right -> left. When we see bigger value, we pop and assign to s3.

If we see a num < s3, we find such a value. Since s3 is initialized as Integer.MIN_VALUE. If we find num < s3, then s3 is updated from stack pop before.

Time Comlexity: O(n). n = nums.length.

Space: O(n).

AC Java:

 1 class Solution {
 2     public boolean find132pattern(int[] nums) {
 3         if(nums == null || nums.length < 3){
 4             return false;
 5         }
 6         
 7         int s3 = Integer.MIN_VALUE;
 8         Stack<Integer> stk = new Stack<>();
 9         for(int i = nums.length - 1; i >= 0; i--){
10             if(nums[i] < s3){
11                 return true;
12             }
13             
14             while(!stk.isEmpty() && stk.peek() < nums[i]){
15                 s3 = stk.pop();
16             }
17             
18             stk.push(nums[i]);
19         }
20         
21         return false;
22     }
23 }

 

posted @ 2017-03-21 08:31  Dylan_Java_NYC  阅读(314)  评论(0编辑  收藏  举报