Leetcode 456.132模式
阿新 • • 發佈:2019-01-15
sta urn solution class ava leet code clas tco
132模式
給定一個整數序列:a1, a2, ..., an,一個132模式的子序列 ai, aj, ak 被定義為:當 i < j < k 時,ai < ak < aj。設計一個算法,當給定有 n 個數字的序列時,驗證這個序列中是否含有132模式的子序列。
註意:n 的值小於15000。
示例1:
輸入: [1, 2, 3, 4]
輸出: False
解釋: 序列中不存在132模式的子序列。
示例 2:
輸入: [3, 1, 4, 2]
輸出: True
解釋: 序列中有 1 個132模式的子序列: [1, 4, 2].
示例 3:
輸入: [-1, 3, 2, 0]
輸出: True
解釋: 序列中有 3 個132模式的的子序列: [-1, 3, 2], [-1, 3, 0] 和 [-1, 2, 0].
1 import java.util.Stack; 2 3 class Solution { 4 public boolean find132pattern(int[] nums) { 5 if(nums.length<3) return false; 6 Stack<Integer> s=new Stack<Integer>();7 int second=Integer.MIN_VALUE; 8 for(int i=nums.length-1;i>=0;i--){ 9 if(nums[i]<second) return true; 10 while(!s.isEmpty()&&nums[i]>s.peek()){ 11 second=s.pop(); 12 } 13 s.push(nums[i]); 14 }15 return false; 16 } 17 }
Leetcode 456.132模式