Skip to content

Commit e59063b

Browse files
refactor 456
1 parent 8b914d5 commit e59063b

File tree

2 files changed

+45
-22
lines changed

2 files changed

+45
-22
lines changed

src/main/java/com/fishercoder/solutions/_456.java

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -33,31 +33,31 @@
3333

3434
public class _456 {
3535

36-
/**Looked at this post: https://discuss.leetcode.com/topic/67881/single-pass-c-o-n-space-and-time-solution-8-lines-with-detailed-explanation
37-
* It scans only once, this is the power of using correct data structure.
38-
* It goes from the right to the left.
39-
* It keeps pushing elements into the stack,
40-
* but it also keeps poping elements out of the stack as long as the current element is bigger than this number.*/
41-
public static boolean find132pattern(int[] nums) {
42-
Deque<Integer> stack = new LinkedList<>();
43-
44-
int s3 = Integer.MIN_VALUE;
45-
for (int i = nums.length - 1; i >= 0; i--) {
46-
if (nums[i] < s3) {
47-
return true;
48-
} else {
49-
while (!stack.isEmpty() && nums[i] > stack.peek()) {
50-
s3 = Math.max(s3, stack.pop());
36+
public static class Solution1 {
37+
/**
38+
* credit: https://discuss.leetcode.com/topic/67881/single-pass-c-o-n-space-and-time-solution-8-lines-with-detailed-explanation
39+
* It scans only once, this is the power of using correct data structure.
40+
* It goes from the right to the left.
41+
* It keeps pushing elements into the stack,
42+
* but it also keeps poping elements out of the stack as long as the current element is bigger than this number.
43+
*/
44+
public boolean find132pattern(int[] nums) {
45+
Deque<Integer> stack = new LinkedList<>();
46+
47+
int s3 = Integer.MIN_VALUE;
48+
for (int i = nums.length - 1; i >= 0; i--) {
49+
if (nums[i] < s3) {
50+
return true;
51+
} else {
52+
while (!stack.isEmpty() && nums[i] > stack.peek()) {
53+
s3 = Math.max(s3, stack.pop());
54+
}
5155
}
56+
stack.push(nums[i]);
5257
}
53-
stack.push(nums[i]);
54-
}
5558

56-
return false;
59+
return false;
60+
}
5761
}
5862

59-
public static void main(String... args) {
60-
int[] nums = new int[]{-1, 3, 2, 0};
61-
System.out.println(find132pattern(nums));
62-
}
6363
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions._456;
4+
import org.junit.BeforeClass;
5+
import org.junit.Test;
6+
7+
import static junit.framework.Assert.assertEquals;
8+
9+
public class _456Test {
10+
private static _456.Solution1 solution1;
11+
12+
@BeforeClass
13+
public static void setup() {
14+
solution1 = new _456.Solution1();
15+
}
16+
17+
@Test
18+
public void test1() {
19+
assertEquals(true, solution1.find132pattern(new int[]{-1, 3, 2, 0}));
20+
21+
}
22+
23+
}

0 commit comments

Comments
 (0)