Skip to content

Commit b3901c8

Browse files
authored
feat: add rust solution to lcof problem: No.30 (doocs#671)
面试题 30. 包含 min 函数的栈
1 parent d848838 commit b3901c8

File tree

2 files changed

+115
-0
lines changed

2 files changed

+115
-0
lines changed

lcof/面试题30. 包含min函数的栈/README.md

+60
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,66 @@ public:
202202
};
203203
```
204204

205+
### **Rust**
206+
207+
```rust
208+
struct MinStack {
209+
items: Vec<i32>,
210+
min: Vec<i32>,
211+
}
212+
213+
214+
/**
215+
* `&self` means the method takes an immutable reference.
216+
* If you need a mutable reference, change it to `&mut self` instead.
217+
*/
218+
impl MinStack {
219+
220+
/** initialize your data structure here. */
221+
fn new() -> Self {
222+
MinStack {
223+
items: Vec::new(),
224+
min: Vec::new(),
225+
}
226+
}
227+
228+
fn push(&mut self, x: i32) {
229+
self.items.push(x);
230+
match self.min.last() {
231+
Some(min) => {
232+
if *min >= x {
233+
self.min.push(x)
234+
}
235+
},
236+
None => self.min.push(x)
237+
}
238+
}
239+
240+
fn pop(&mut self) {
241+
if self.items.pop().unwrap() == *self.min.last().unwrap() {
242+
self.min.pop();
243+
}
244+
}
245+
246+
fn top(&self) -> i32 {
247+
*self.items.last().unwrap()
248+
}
249+
250+
fn min(&self) -> i32 {
251+
*self.min.last().unwrap()
252+
}
253+
}
254+
255+
/**
256+
* Your MinStack object will be instantiated and called as such:
257+
* let obj = MinStack::new();
258+
* obj.push(x);
259+
* obj.pop();
260+
* let ret_3: i32 = obj.top();
261+
* let ret_4: i32 = obj.min();
262+
*/
263+
```
264+
205265
### **...**
206266

207267
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
struct MinStack {
2+
items: Vec<i32>,
3+
min: Vec<i32>,
4+
}
5+
6+
7+
/**
8+
* `&self` means the method takes an immutable reference.
9+
* If you need a mutable reference, change it to `&mut self` instead.
10+
*/
11+
impl MinStack {
12+
13+
/** initialize your data structure here. */
14+
fn new() -> Self {
15+
MinStack {
16+
items: Vec::new(),
17+
min: Vec::new(),
18+
}
19+
}
20+
21+
fn push(&mut self, x: i32) {
22+
self.items.push(x);
23+
match self.min.last() {
24+
Some(min) => {
25+
if *min >= x {
26+
self.min.push(x)
27+
}
28+
},
29+
None => self.min.push(x)
30+
}
31+
}
32+
33+
fn pop(&mut self) {
34+
if self.items.pop().unwrap() == *self.min.last().unwrap() {
35+
self.min.pop();
36+
}
37+
}
38+
39+
fn top(&self) -> i32 {
40+
*self.items.last().unwrap()
41+
}
42+
43+
fn min(&self) -> i32 {
44+
*self.min.last().unwrap()
45+
}
46+
}
47+
48+
/**
49+
* Your MinStack object will be instantiated and called as such:
50+
* let obj = MinStack::new();
51+
* obj.push(x);
52+
* obj.pop();
53+
* let ret_3: i32 = obj.top();
54+
* let ret_4: i32 = obj.min();
55+
*/

0 commit comments

Comments
 (0)