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
54
// @Title: 包含min函数的栈 (包含min函数的栈 LCOF)
// @Author: 15816537946@163.com
// @Date: 2022-01-31 13:24:34
// @Runtime: 0 ms
// @Memory: 5.7 MB
// 实现二,通过辅助栈保证 min(x) 满足 O(1) 要求
#[derive(Default)]
struct MinStack {
    data: Vec<i32>,
    helper: Vec<i32>,
}

/**
 * `&self` means the method takes an immutable reference.
 * If you need a mutable reference, change it to `&mut self` instead.
 */
impl MinStack {
    /** initialize your data structure here. */
    fn new() -> Self {
        Default::default()
    }

    fn push(&mut self, x: i32) {
        self.data.push(x);

        if self.helper.is_empty() || *self.helper.last().unwrap() >= x {
            self.helper.push(x);
        }
    }

    fn pop(&mut self) {
        if *self.helper.last().unwrap() == self.data.pop().unwrap() {
            self.helper.pop();
        }
    }

    fn top(&self) -> i32 {
        *self.data.last().unwrap()
    }

    fn min(&self) -> i32 {
        *self.helper.last().unwrap()
    }
}

/*
 * Your MinStack object will be instantiated and called as such:
 * let obj = MinStack::new();
 * obj.push(x);
 * obj.pop();
 * let ret_3: i32 = obj.top();
 * let ret_4: i32 = obj.min();
 */