描述
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.
n will be less than 20,000.
解題代碼
public class Solution {
/**
* @param nums a list of n integers
* @return true if there is a 132 pattern or false
*/
public boolean find132pattern(int[] nums) {
// Write your code here
int n = nums.length;
int i=0,j=0,k=0;
int third = Integer.MIN_VALUE;
Stack<Integer> s = new Stack<Integer>();
if(n < 3)
return false;
for(i=n-1;i>=0;i--){
if(nums[i] < third)
return true;
else
//second值和third值越接近越優
while(!s.empty() && nums[i] > s.peek()){
third = s.pop();
}
s.push(nums[i]);
}
return false;
}
}
筆記/思路
stack s裏面維持的是一個(從棧頂到棧底)升序的排列,越往棧底,越接近數組尾部。也就是說,棧頂存的是棧中最小的值。
可以理解爲棧中存儲的是“132”中的預備“2”值。
從後向前 遍歷數組,每當有值大於棧頂的值,那麼就滿足“132”模式中的“32”,彈出“2”,保存在變量third(第三個值)中,下一次循環如果當前值小於“2”值,那麼就滿足“132”的“1”了,這樣就完成了查找“132”值。