Question:
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.
Solution1: Brute Force
class Solution {
public boolean find132pattern(int[] nums) {
if (nums.length < 3) {
return false;
}
int min_i = Integer.MAX_VALUE;
for (int j = 0; j < nums.length - 1; j++) {
min_i = Math.min(min_i, nums[j]);
for (int k = j + 1; k < nums.length; k++) {
if (nums[j] > nums[k] && min < nums[k]) {
return true;
}
}
}
return false;
}
}
Note1:
- Iterate the numbers in the array and take each element as the largest one (nums[j]), since the smallest one (nums[i]) can only be ahead of nums[j], so we can also fixed it. For each num[j], loop through all the element behind it to find the one in the middle (nums[k]).
Solution2(Stack):
class Solution {
public boolean find132pattern(int[] nums) {
if (nums.length < 3) {
return false;
}
int[] minArray = new int[nums.length];
int min_i = Integer.MAX_VALUE;
Stack<Integer> stack = new Stack<>();
for (int j = 0; j < nums.length; j++) {
min_i = Math.min(min_i, nums[j]);
minArray[j] = min_i;
}
for (int k = nums.length - 1; k >= 1; k--) {
if ( nums[k] > minArray[k] && (stack.isEmpty() || stack.peek() > nums[k])) {
stack.push(nums[k]);
}
else if (!stack.isEmpty() && nums[k] > minArray[k] && stack.peek() < nums[k] {
if (stack.peek() > minArray[k]) {
return true;
} else {
stack.pop();
}
}
}
return false;
}
}