-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmin_stack.rs
More file actions
53 lines (48 loc) · 1.15 KB
/
min_stack.rs
File metadata and controls
53 lines (48 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
pub struct MinStack {
stack: Vec<i64>,
min: i64,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl MinStack {
pub fn new() -> Self {
MinStack {
stack: Vec::new(),
min: 0,
}
}
pub fn push(&mut self, val: i32) {
let val = val as i64;
if self.stack.is_empty() {
self.stack.push(0);
self.min = val.into();
} else {
self.stack.push(val - self.min);
if val < self.min {
self.min = val;
}
}
}
pub fn pop(&mut self) {
if !self.stack.is_empty() {
let pop = self.stack.last().copied().unwrap();
self.stack.pop();
if pop < 0 {
self.min -= pop;
}
}
}
pub fn top(&self) -> i32 {
let top = *self.stack.last().unwrap();
if top > 0 {
return (top + self.min) as i32;
} else {
return self.min as i32;
}
}
pub fn get_min(&self) -> i32 {
self.min as i32
}
}