Skip to content

Commit 88f4c84

Browse files
authored
Update 132 Pattern.java
1 parent 0cb7779 commit 88f4c84

File tree

1 file changed

+18
-20
lines changed

1 file changed

+18
-20
lines changed

Medium/132 Pattern.java

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,23 @@
11
class Solution {
2-
public boolean find132pattern(int[] nums) {
3-
if (nums.length < 3) {
4-
return false;
5-
}
6-
int[] minTillIndex = new int[nums.length];
7-
minTillIndex[0] = nums[0];
8-
for (int idx = 1; idx < nums.length; idx++) {
9-
minTillIndex[idx] = Math.min(minTillIndex[idx - 1], nums[idx]);
10-
}
11-
Stack<Integer> stack = new Stack<>();
12-
for (int idx = nums.length - 1; idx >= 0; idx--) {
13-
if (nums[idx] > minTillIndex[idx]) {
14-
while (!stack.isEmpty() && stack.peek() <= minTillIndex[idx]) {
15-
stack.pop();
2+
public boolean find132pattern(int[] nums) {
3+
int n = nums.length;
4+
int[] uptoIdxMin = new int[n];
5+
uptoIdxMin[0] = nums[0];
6+
for (int i = 1; i < n; i++) {
7+
uptoIdxMin[i] = Math.min(uptoIdxMin[i - 1], nums[i]);
168
}
17-
if (!stack.isEmpty() && stack.peek() < nums[idx]) {
18-
return true;
9+
Stack<Integer> stack = new Stack<>();
10+
for (int i = n - 1; i >= 0; i--) {
11+
if (nums[i] > uptoIdxMin[i]) {
12+
while (!stack.isEmpty() && stack.peek() <= uptoIdxMin[i]) {
13+
stack.pop();
14+
}
15+
if (!stack.isEmpty() && stack.peek() < nums[i]) {
16+
return true;
17+
}
18+
stack.push(nums[i]);
19+
}
1920
}
20-
stack.push(nums[idx]);
21-
}
21+
return false;
2222
}
23-
return false;
24-
}
2523
}

0 commit comments

Comments
 (0)