Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit49fbca1

Browse files
format
1 parent747886b commit49fbca1

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

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
packagecom.fishercoder.solutions;
22

3-
importjava.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+
importjava.util.Deque;
4+
importjava.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
publicclass_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
publicstaticbooleanfind132pattern(int[]nums) {
32-
Stack<Integer>stack =newStack();
42+
Deque<Integer>stack =newLinkedList<>();
3343

3444
ints3 =Integer.MIN_VALUE;
3545
for (inti =nums.length-1;i >=0;i--){
3646
if (nums[i] <s3)returntrue;
37-
elsewhile (!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)

[8]ページ先頭

©2009-2025 Movatter.jp