Given a sequence of integers: a . 1 , a 2 , ..., a n- , subsequence a a 132 mode I , a J , a K is defined as: When I <J <K, a I <a K <a J . Design an algorithm, when there is given a sequence of n numbers, to verify whether this sequence contains a subsequence 132 mode.
Note: the value of n is less than 15,000.
Example 1:
Input: [1, 2, 3, 4]
Output: False
Explanation: absence pattern sequence 132 sequences.
Example 2:
Input: [3, 1, 4, 2]
Output: True
Explanation: the sequence has a sequence pattern 132: [1, 4, 2].
Example 3:
Input: [-1, 3, 2, 0]
Output: True
Explanation: sequence has three sequences 132 modes: [-1, 3, 2], [-1, 3, 0] and [-1 , 2, 0].
Solution 2
2.1 ideas
Violence, traversing from the tail to the head, if the current element is the last element 132, respectively, the front and center must have less than a current element and an element is greater than the current element.
Stack, reference https://leetcode-cn.com/problems/132-pattern/solution/132mo-shi-by-leetcode-2/
2.2 Code
- violence
class Solution {
public boolean find132pattern(int[] nums) {
for(int i = nums.length-1;i>=2;i--){
int tail = nums[i];
boolean hasPeek = false;
for(int j = i-1;j>=0;j--){
if(nums[j]>tail) hasPeek = true;
else if(hasPeek&&nums[j]<tail) return true;
}
}
return false;
}
}
- Stack
public class Solution {
public boolean find132pattern(int[] nums) {
if (nums.length < 大专栏 leetcode456-132模式3)
return false;
Stack<Integer> stack = new Stack<>();
int[] min = new int[nums.length];
min[0] = nums[0];
for (int i = 1; i < nums.length; i++)
min[i] = Math.min(min[i - 1], nums[i]);
for (int j = nums.length - 1; j >= 0; j--) {
if (nums[j] > min[j]) {
while (!stack.isEmpty() && stack.peek() <= min[j])
stack.pop();
if (!stack.isEmpty() && stack.peek() < nums[j])
return true;
stack.push(nums[j]);
}
}
return false;
}
}