We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent d643ff0 commit 357f056Copy full SHA for 357f056
stack/find132pattern.java
@@ -0,0 +1,25 @@
1
+class Solution {
2
+// O(N) time and O(N) space
3
+ public boolean find132pattern(int[] nums) {
4
+ if (nums == null || nums.length < 3) return false;
5
+
6
+ int[] minArray = new int[nums.length];
7
+ minArray[0] = nums[0];
8
+ for (int i=1; i<nums.length; i++) {
9
+ minArray[i] = Math.min(nums[i], minArray[i-1]);
10
+ }
11
+ Stack<Integer> kStack = new Stack<>(); // stack to keep the middle element 2
12
+ kStack.push(nums[nums.length - 1]);
13
14
+ for(int j=nums.length - 1; j>=0; j--) {
15
+ while (!kStack.isEmpty() && kStack.peek() <= minArray[j]) {
16
+ kStack.pop(); // since k(2) should be greater than j(1)
17
18
+ if (!kStack.isEmpty() && kStack.peek() < nums[j]) {
19
+ return true;
20
21
+ kStack.push(nums[j]);
22
23
+ return false;
24
25
+}
0 commit comments