456. 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]. // solution 1 class Solution { public boolean find132pattern(int[] nums) { // a brute force way is to try all possible solutions , time is n * n -1 * n -2 , roughly around n ^ 3 // compare all the values // ai < aj , ak < aj, ai < ak // 81 / 95 test cases passed. tle for(int i = 0; i < nums.length - 2; i++){ for(int j = i + 1; j < nums.length - 1; j++){ for(int k = j + 1; k < nums.length; k++){ int ai = nums[i]; int aj = nums[j]; int ak = nums[k]; if(ai < aj && ak < aj && ai < ak) return true; } } } return false; } } // sol 2 https://leetcode.com/problems/132-pattern/discuss/94077/Java-O(n)-solution-using-stack-in-detail-explanation https://leetcode.com/problems/132-pattern/solution/ http://www.cnblogs.com/grandyang/p/6081984.html 思路是我们维护一个栈和一个变量third,其中third就是第三个数字,也是pattern 132中的2,栈里面按顺序放所有大于third的数字,也是pattern 132中的3,那么我们在遍历的时候,如果当前数字小于third,即pattern 132中的1找到了,我们直接返回true即可,因为已经找到了,注意我们应该从后往前遍历数组。如果当前数字大于栈顶元素,那么我们按顺序将栈顶数字取出,赋值给third,然后将该数字压入栈,这样保证了栈里的元素仍然都是大于third的,我们想要的顺序依旧存在,进一步来说,栈里存放的都是可以维持second > third的second值,其中的任何一个值都是大于当前的third值,如果有更大的值进来,那就等于形成了一个更优的second > third的这样一个组合,并且这时弹出的third值比以前的third值更大,为什么要保证third值更大,因为这样才可以更容易的满足当前的值first比third值小这个条件 // passed 87 / 95 cases class Solution { public boolean find132pattern(int[] nums) { if(nums == null || nums.length < 3) return false; // stack stores all the nums bigger than lastNumber Stack<Integer> stack = new Stack<>(); int lastNumber = nums[nums.length - 1]; for(int i = nums.length - 2; i >= 0; i--){ // if current number is bigger than the lastNumber , push it to the stack // if the stack is empty, push it to the stack , if the stack is not empty, // if stack.peek() < current number, then last number = stack.peek(), stack push the current number // if the stack.peek() > current number , do nothing // if current number is smaller than the lastNumber , // if the stack is empty, do nothing // if the stack is not empty, return true; if(nums[i] > lastNumber){ if(stack.isEmpty()){ stack.push(nums[i]); }else{ if(stack.peek() < nums[i]){ lastNumber = stack.pop(); stack.push(nums[i]); } } }else if(nums[i] < lastNumber){ if(stack.isEmpty()){ lastNumber = nums[i]; }else{ return true; } }else{ continue; } } return false; } }
posted on 2018-11-09 10:20 猪猪🐷 阅读(109) 评论(0) 收藏 举报
浙公网安备 33010602011771号