原题链接在这里:https://leetcode.com/problems/132-pattern/#/solutions
题目:
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].
题解:
利用Stack<Interval> stk先固定min, 在遇到比stk.peek().min更小的数num就push进新的最小地标new Interval(num, num).
在遇到比stk.peek().min大的数时 先判断是否同时比stk.peek().max小, 若是就return true.
若比stk.peek.max还大就更新stk.peek().max. 此时的min肯定是最小的min, 如果num还比stk下面的max大,那就包含了下面的Interval, pop出来被包含的Interval后, 若是num > stk.peek().min 也return true.
Time Comlexity: O(n). Space: O(n).
AC Java:
1 public class Solution { 2 public boolean find132pattern(int[] nums) { 3 Stack<Interval> stk = new Stack<Interval>(); 4 for(int num : nums){ 5 if(stk.isEmpty() || num<stk.peek().min){ 6 stk.push(new Interval(num, num)); 7 }else if(num>stk.peek().min){ 8 Interval top = stk.pop(); 9 if(num < top.max){ 10 return true; 11 }else{ 12 top.max = num; 13 while(!stk.isEmpty() && num>=stk.peek().max){ 14 stk.pop(); 15 } 16 if(!stk.isEmpty() && num>stk.peek().min){ 17 return true; 18 } 19 stk.push(top); 20 } 21 } 22 } 23 return false; 24 } 25 } 26 27 class Interval{ 28 int min; 29 int max; 30 public Interval(int min, int max){ 31 this.min = min; 32 this.max = max; 33 } 34 }