|
| 1 | +#[derive(Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq, Hash)] |
| 2 | +struct Element { |
| 3 | + val: i32, |
| 4 | + min: i32, |
| 5 | +} |
| 6 | + |
| 7 | +impl Element { |
| 8 | + |
| 9 | + fn new(val: i32, min: i32) -> Self { |
| 10 | + Self { val, min } |
| 11 | + } |
| 12 | + |
| 13 | +} |
| 14 | + |
| 15 | +/// Design a stack that supports push, pop, top, and retrieving the minimum |
| 16 | +/// element in constant time. |
| 17 | +/// |
| 18 | +/// Implement the `MinStack` class: |
| 19 | +/// |
| 20 | +/// * `MinStack()` initializes the stack object. |
| 21 | +/// * `void push(int val)` pushes the element `val` on the the stack. |
| 22 | +/// * `void pop()` removes the element on the top of the stack. |
| 23 | +/// * `int top()` gets the top element of the stack. |
| 24 | +/// * `int getMin()` retrieves the minimum element in the stack. |
| 25 | +/// |
| 26 | +/// You must implement a solution with `O(1)` time complexity for each |
| 27 | +/// funtion. |
| 28 | +struct MinStack { |
| 29 | + items: Vec<Element> |
| 30 | +} |
| 31 | + |
| 32 | +impl MinStack { |
| 33 | + |
| 34 | + fn new() -> Self { |
| 35 | + Self { items: Vec::new() } |
| 36 | + } |
| 37 | + |
| 38 | + fn push(&mut self, val: i32) { |
| 39 | + let element; |
| 40 | + if self.items.is_empty() { |
| 41 | + element = Element::new(val, val); |
| 42 | + } else { |
| 43 | + let min = self.get_min(); |
| 44 | + element = Element::new(val, val.min(min)); |
| 45 | + } |
| 46 | + self.items.push(element); |
| 47 | + } |
| 48 | + |
| 49 | + fn pop(&mut self) { |
| 50 | + self.items.pop(); |
| 51 | + } |
| 52 | + |
| 53 | + fn top(&self) -> i32 { |
| 54 | + let n = self.items.len(); |
| 55 | + if n == 0 { 0 } |
| 56 | + else { self.items[n-1].val } |
| 57 | + } |
| 58 | + |
| 59 | + fn get_min(&self) -> i32 { |
| 60 | + let n = self.items.len(); |
| 61 | + if n == 0 { 0 } |
| 62 | + else { self.items[n-1].min } |
| 63 | + } |
| 64 | + |
| 65 | +} |
| 66 | + |
| 67 | +#[cfg(test)] |
| 68 | +mod tests { |
| 69 | + use super::MinStack; |
| 70 | + |
| 71 | + #[test] |
| 72 | + fn example_1() { |
| 73 | + let mut min_stack = MinStack::new(); |
| 74 | + min_stack.push(-2); |
| 75 | + min_stack.push(0); |
| 76 | + min_stack.push(-3); |
| 77 | + let result = min_stack.get_min(); |
| 78 | + assert_eq!(result, -3); |
| 79 | + min_stack.pop(); |
| 80 | + let result = min_stack.top(); |
| 81 | + assert_eq!(result, 0); |
| 82 | + let result = min_stack.get_min(); |
| 83 | + assert_eq!(result, -2); |
| 84 | + } |
| 85 | + |
| 86 | +} |
0 commit comments