File tree 2 files changed +43
-0
lines changed
2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ package medium ;
2
+
3
+ import java .util .Stack ;
4
+
5
+ public class _132Pattern {
6
+ //a brute force method got TLE:
7
+ public boolean find132pattern_TLE (int [] nums ) {
8
+ for (int i = 0 ; i < nums .length -2 ; i ++){
9
+ for (int j = i +1 ; j < nums .length -1 ; j ++){
10
+ if (nums [j ] < nums [i ]) continue ;
11
+ for (int k = j +1 ; k < nums .length ; k ++){
12
+ if (nums [k ] < nums [j ] && nums [i ] < nums [k ]) return true ;
13
+ }
14
+ }
15
+ }
16
+ return false ;
17
+ }
18
+
19
+
20
+ /**Looked at this post: https://discuss.leetcode.com/topic/67881/single-pass-c-o-n-space-and-time-solution-8-lines-with-detailed-explanation
21
+ * It scans only once, this is the power of using correct data structure.
22
+ * 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.*/
23
+ public static boolean find132pattern (int [] nums ) {
24
+ Stack <Integer > stack = new Stack ();
25
+
26
+ int s3 = Integer .MIN_VALUE ;
27
+ for (int i = nums .length -1 ; i >= 0 ; i --){
28
+ if (nums [i ] < s3 ) return true ;
29
+ else while (!stack .isEmpty () && nums [i ] > stack .peek ()){
30
+ s3 = Math .max (s3 , stack .pop ());
31
+ }
32
+ stack .push (nums [i ]);
33
+ }
34
+
35
+ return false ;
36
+ }
37
+
38
+ public static void main (String ...args ){
39
+ int [] nums = new int []{-1 , 3 , 2 , 0 };
40
+ System .out .println (find132pattern (nums ));
41
+ }
42
+ }
Original file line number Diff line number Diff line change 2
2
| # | Title | Solutions | Time | Space | Difficulty | Tag | Notes
3
3
|-----|----------------|---------------|---------------|---------------|-------------|--------------|-----
4
4
|459|[ Repeated Substring Pattern] ( https://leetcode.com/problems/repeated-substring-pattern/ ) |[ Solution] ( ../../blob/master/EASY/src/easy/RepeatedSubstringPattern.java ) | O(n)|O(n) | Easy| KMP
5
+ |456|[ 132 Pattern] ( https://leetcode.com/problems/132-pattern/ ) |[ Solution] ( ../../blob/master/MEDIUM/src/medium/_132Pattern.java ) | O(n) |O(n) | Medium| Stack
5
6
| 455| [ Assign Cookies] ( https://leetcode.com/problems/assign-cookies/ ) | [ Solution] ( ../../blob/master/EASY/src/easy/AssignCookies.java ) | O(n)| O(1) | Easy|
6
7
| 453| [ Minimum Moves to Equal Array Elements] ( https://leetcode.com/problems/minimum-moves-to-equal-array-elements/ ) | [ Solution] ( ../../blob/master/EASY/src/easy/MinimumMovestoEqualArrayElements.java ) | O(n)| O(1) | Easy|
7
8
|447|[ Number of Boomerangs] ( https://leetcode.com/problems/number-of-boomerangs/ ) |[ Solution] ( ../../blob/master/EASY/src/easy/NumberofBoomerangs.java ) | O(n^2)|O(n) | Easy| HashMap
You can’t perform that action at this time.
0 commit comments