Skip to content

Commit 35ef313

Browse files
committed
Added solution of problem 155
1 parent 0f460e7 commit 35ef313

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

src/solutions/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ pub mod s0150_evaluate_reverse_polish_notation;
8989
pub mod s0151_reverse_words_in_a_string;
9090
pub mod s0152_maximum_product_subarray;
9191
pub mod s0153_find_minimum_in_rotated_sorted_array;
92+
pub mod s0155_min_stack;
9293
pub mod s0231_power_of_two;
9394
pub mod s0232_implement_queue_using_stacks;
9495
pub mod s0234_palindrome_linked_list;

src/solutions/s0155_min_stack.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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+
}

0 commit comments

Comments
 (0)