|
33 | 33 |
|
34 | 34 | public class _456 {
|
35 | 35 |
|
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 | + } |
51 | 55 | }
|
| 56 | + stack.push(nums[i]); |
52 | 57 | }
|
53 |
| - stack.push(nums[i]); |
54 |
| - } |
55 | 58 |
|
56 |
| - return false; |
| 59 | + return false; |
| 60 | + } |
57 | 61 | }
|
58 | 62 |
|
59 |
| - public static void main(String... args) { |
60 |
| - int[] nums = new int[]{-1, 3, 2, 0}; |
61 |
| - System.out.println(find132pattern(nums)); |
62 |
| - } |
63 | 63 | }
|
0 commit comments