File tree 2 files changed +78
-0
lines changed
main/java/leetcode/medium
test/java/leetcode/medium
2 files changed +78
-0
lines changed Original file line number Diff line number Diff line change
1
+ package leetcode .medium ;
2
+
3
+ import java .util .Stack ;
4
+
5
+ public class MinStack {
6
+
7
+ Stack <Integer > stack ;
8
+ Stack <Integer > minStack ;
9
+
10
+ public MinStack () {
11
+ stack = new Stack <>();
12
+ minStack = new Stack <>();
13
+ }
14
+
15
+ public void push (int val ) {
16
+ stack .push (val );
17
+
18
+ // If the minStack is empty or the new value is less than or equal to
19
+ // the top of the minStack, push it onto the minStack
20
+ if (minStack .isEmpty () || val <= minStack .peek ()) {
21
+ minStack .push (val );
22
+ }
23
+ }
24
+
25
+ public void pop () {
26
+ int poppedValue = stack .pop ();
27
+
28
+ // If the popped value is equal to the top of the minStack,
29
+ // pop it from the minStack as well
30
+ if (poppedValue == minStack .peek ()) {
31
+ minStack .pop ();
32
+ }
33
+ }
34
+
35
+ public int top () {
36
+ return stack .peek ();
37
+ }
38
+
39
+ public int getMin () {
40
+ return minStack .peek ();
41
+ }
42
+ }
Original file line number Diff line number Diff line change
1
+ package leetcode .medium ;
2
+
3
+ import org .junit .jupiter .api .Test ;
4
+
5
+ import static org .junit .jupiter .api .Assertions .*;
6
+
7
+ class MinStackTest {
8
+
9
+ @ Test
10
+ void testMinStack1 () {
11
+ MinStack minStack = new MinStack ();
12
+ minStack .push (-2 );
13
+ minStack .push (0 );
14
+ minStack .push (-3 );
15
+ assertEquals (-3 , minStack .getMin ());
16
+ minStack .pop ();
17
+ assertEquals (0 , minStack .top ());
18
+ assertEquals (-2 , minStack .getMin ());
19
+ }
20
+
21
+ @ Test
22
+ void testMinStack2 () {
23
+ MinStack minStack = new MinStack ();
24
+ minStack .push (-1 );
25
+ minStack .push (-2 );
26
+ minStack .push (-3 );
27
+ minStack .push (0 );
28
+ minStack .push (2 );
29
+ assertEquals (-3 , minStack .getMin ());
30
+ assertEquals (2 , minStack .top ());
31
+ minStack .pop ();
32
+ assertEquals (0 , minStack .top ());
33
+ assertEquals (-3 , minStack .getMin ());
34
+ }
35
+
36
+ }
You can’t perform that action at this time.
0 commit comments