File tree 1 file changed +35
-35
lines changed
src/main/java/com/fishercoder/solutions 1 file changed +35
-35
lines changed Original file line number Diff line number Diff line change 1
1
package com .fishercoder .solutions ;
2
2
3
-
4
3
import java .util .Stack ;
5
4
6
5
/**
25
24
26
25
public class _155 {
27
26
28
- public static class MinStack {
29
- private Stack <Integer > stack ;
30
- private int min ;
31
-
32
- /**
33
- * initialize your data structure here.
34
- */
35
- public MinStack () {
36
- stack = new Stack ();
37
- min = Integer .MAX_VALUE ;
38
- }
27
+ public static class Solution1 {
28
+ class MinStack {
29
+ private Stack <Integer > stack ;
30
+ private int min ;
39
31
40
- public void push ( int x ) {
41
- /**All the trick happens here, we push the second minimum number onto the stack before we push the newer one,
42
- * this way, when popping, we could always get the next minimum one in constant time.* /
43
- if ( x <= min ) {
44
- stack . push ( min );
45
- min = x ;
32
+ /**
33
+ * initialize your data structure here.
34
+ */
35
+ public MinStack ( ) {
36
+ stack = new Stack ( );
37
+ min = Integer . MAX_VALUE ;
46
38
}
47
- stack .push (x );
48
- }
49
39
50
- public void pop () {
51
- if (min == stack .peek ()) {
52
- stack .pop ();
53
- min = stack .pop ();
54
- } else {
55
- stack .pop ();
40
+ public void push (int x ) {
41
+ /**All the trick happens here, we push the second minimum number onto the stack before we push the newer one,
42
+ * this way, when popping, we could always get the next minimum one in constant time.*/
43
+ if (x <= min ) {
44
+ stack .push (min );
45
+ min = x ;
46
+ }
47
+ stack .push (x );
56
48
}
57
- if (stack .isEmpty ()) {
58
- min = Integer .MAX_VALUE ;
49
+
50
+ public void pop () {
51
+ if (min == stack .peek ()) {
52
+ stack .pop ();
53
+ min = stack .pop ();
54
+ } else {
55
+ stack .pop ();
56
+ }
57
+ if (stack .isEmpty ()) {
58
+ min = Integer .MAX_VALUE ;
59
+ }
59
60
}
60
- }
61
61
62
- public int top () {
63
- return stack .peek ();
64
- }
62
+ public int top () {
63
+ return stack .peek ();
64
+ }
65
65
66
- public int getMin () {
67
- return min ;
66
+ public int getMin () {
67
+ return min ;
68
+ }
68
69
}
69
70
}
70
-
71
71
}
You can’t perform that action at this time.
0 commit comments