File tree Expand file tree Collapse file tree 2 files changed +58
-0
lines changed Expand file tree Collapse file tree 2 files changed +58
-0
lines changed Original file line number Diff line number Diff line change @@ -89,6 +89,7 @@ pub mod s0150_evaluate_reverse_polish_notation;
89
89
pub mod s0151_reverse_words_in_a_string;
90
90
pub mod s0152_maximum_product_subarray;
91
91
pub mod s0153_find_minimum_in_rotated_sorted_array;
92
+ pub mod s0155_min_stack;
92
93
pub mod s0231_power_of_two;
93
94
pub mod s0232_implement_queue_using_stacks;
94
95
pub mod s0234_palindrome_linked_list;
Original file line number Diff line number Diff line change
1
+ use std:: collections:: VecDeque ;
2
+
3
+ pub struct MinStack {
4
+ minimum : i32 ,
5
+ stack : VecDeque < i32 > ,
6
+ }
7
+
8
+ impl MinStack {
9
+ pub fn new ( ) -> Self {
10
+ MinStack {
11
+ minimum : i32:: MAX ,
12
+ stack : VecDeque :: new ( ) ,
13
+ }
14
+ }
15
+
16
+ pub fn push ( & mut self , val : i32 ) {
17
+ self . minimum = std:: cmp:: min ( self . minimum , val) ;
18
+ self . stack . push_front ( val) ;
19
+ }
20
+
21
+ pub fn pop ( & mut self ) {
22
+ self . stack . pop_front ( ) ;
23
+ self . minimum = match self . stack . iter ( ) . min ( ) {
24
+ Some ( m) => * m,
25
+ None => i32:: MAX ,
26
+ }
27
+ }
28
+
29
+ pub fn top ( & self ) -> i32 {
30
+ * self . stack . front ( ) . unwrap ( )
31
+ }
32
+
33
+ pub fn get_min ( & self ) -> i32 {
34
+ self . minimum
35
+ }
36
+ }
37
+
38
+ #[ cfg( test) ]
39
+ mod test {
40
+ use super :: * ;
41
+
42
+ #[ test]
43
+ fn test_case_1 ( ) {
44
+ let mut stack = MinStack :: new ( ) ;
45
+
46
+ stack. push ( -2 ) ;
47
+ stack. push ( 0 ) ;
48
+ stack. push ( -3 ) ;
49
+
50
+ assert_eq ! ( stack. get_min( ) , -3 ) ;
51
+
52
+ stack. pop ( ) ;
53
+
54
+ assert_eq ! ( stack. top( ) , 0 ) ;
55
+ assert_eq ! ( stack. get_min( ) , -2 ) ;
56
+ }
57
+ }
You can’t perform that action at this time.
0 commit comments