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.
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].
public class Solution {
public boolean find132pattern(int[] nums) {
int[] arr = Arrays.copyOf(nums, nums.length);
for(int i=1; i<nums.length; i++){
//记录nums[0,i) 即nums[i] 之前, nums[0,i-1]里的最小值,即题目里的ai
arr[i] = Math.min(nums[i-1], arr[i-1]);
}
for(int j=nums.length-1, top = nums.length; j>= 0; j--) {
// ai < ak < aj 即 ai< aj 所有不满足的直接跳过。
if(nums[j] <= arr[j]) continue;
// 已知ai, 那么找一个比ai大,又尽可能小的数ak, 找满足ai<ak<aj就最可能。
while(top < nums.length && arr[top] <= arr[j]) top++;
// 找到ak后,比较是否满足ak < aj 满足就返回true
if(top < nums.length && nums[j] > arr[top]) return true;
// 更新栈顶元素ak, top++表示pop, --top表示push
arr[--top] = nums[j];
}
return false;
}
}
// 1 3 5 0 3 6 aj
// 1 1 1 0 0 0 ai
// 0 0 0 0 3 6 ak
// https://discuss.leetcode.com/topic/68242/java-solutions-from-o-n-3-to-o-n-for-132-pattern/2
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。