[LeetCode][456. 132 Pattern] 4 Approaches: BF O(n^3), BF O(n^2), TreeMap, Monotonic Stack
By Long Luo
This article is the solution 4 Approaches: BF O(n^3), BF O(n^2), TreeMap, Monotonic Stack of Problem 456. 132 Pattern .
Here are 4 approaches to solve this problem in Java: BF \(O(n^3)\) , BF \(O(n^2)\) , TreeMap, Monotonic Stack.
BF O(n^3)
It’s easy to use 3 loops to find \(3\) elements which is \(132\) pattern, but the time complexity is \(O(n^3)\) , so it wouldn’t accepted as TLE!1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public boolean find132pattern_bf(int[] nums) {
int len = nums.length;
if (len < 3) {
return false;
}
for (int i = 0; i < len - 2; i++) {
for (int j = i + 1; j < len - 1; j++) {
for (int k = j + 1; k < len; k++) {
if (nums[i] < nums[k] && nums[k] < nums[j]) {
return true;
}
}
}
}
return false;
}
Analysis
- Time Complexity: \(O(n^3)\).
- Space Complexity: \(O(1)\).
BF O(n^2)
Noticed that \(\textit{nums}[j]\) is the peak of the \(3\) elements, suppose the current element is \(\textit{nums}[j]\), we have to find the element \(\textit{nums}[k]\) that is smaller than \(\textit{nums}[j]\) after \(j\), and the element \(\textit{nums}[i]\) that is smaller than \(\textit{nums}[k]\) before \(j\).
Scan left from \(j\) to \(0\), \(0 \le i \lt j\), whether there is \(\textit{nums}[i] < \textit{nums}[j]\), update the mininum \(\textit{leftMin}\);
Scan right from \(j\) to the end, \(j + 1 \le k \lt len\), whether there is \(\textit{nums}[k] < \textit{nums}[j]\), update the maxinum \(\textit{rightMax}\);
If exists and \(\textit{leftMin} < \textit{rightMax}\) , return true.