Skip to content

Commit 49fbca1

Browse files
format
1 parent 747886b commit 49fbca1

File tree

1 file changed

+19
-7
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+19
-7
lines changed

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

+19-7
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
package com.fishercoder.solutions;
22

3-
import java.util.Stack;
4-
/**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.
3+
import java.util.Deque;
4+
import java.util.LinkedList;
5+
/**
6+
* 456. 132 Pattern
7+
*
8+
* Given a sequence of n integers a1, a2, ..., an,
9+
* a 132 pattern is a subsequence ai, aj, ak such that i < j < k and ai < ak < aj.
10+
* Design an algorithm that takes a list of n numbers as input and checks whether there is a 132 pattern in the list.
511
612
Note: n will be less than 15,000.
713
@@ -22,20 +28,26 @@
2228
2329
Output: True
2430
25-
Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].*/
31+
Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
32+
*/
33+
2634
public class _456 {
2735

2836
/**Looked at this post: https://discuss.leetcode.com/topic/67881/single-pass-c-o-n-space-and-time-solution-8-lines-with-detailed-explanation
2937
* It scans only once, this is the power of using correct data structure.
30-
* It goes from the right to the left. It keeps pushing elements into the stack, but it also keeps poping elements out of the stack as long as the current element is bigger than this number.*/
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.*/
3141
public static boolean find132pattern(int[] nums) {
32-
Stack<Integer> stack = new Stack();
42+
Deque<Integer> stack = new LinkedList<>();
3343

3444
int s3 = Integer.MIN_VALUE;
3545
for (int i = nums.length-1; i >= 0; i--){
3646
if (nums[i] < s3) return true;
37-
else while (!stack.isEmpty() && nums[i] > stack.peek()){
38-
s3 = Math.max(s3, stack.pop());
47+
else {
48+
while (!stack.isEmpty() && nums[i] > stack.peek()){
49+
s3 = Math.max(s3, stack.pop());
50+
}
3951
}
4052
stack.push(nums[i]);
4153
}

0 commit comments

Comments
 (0)