Skip to content

feat: add rust solution to lcof problem: No.30 #671

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions lcof/面试题30. 包含min函数的栈/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,66 @@ public:
};
```

### **Rust**

```rust
struct MinStack {
items: Vec<i32>,
min: 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 {
MinStack {
items: Vec::new(),
min: Vec::new(),
}
}

fn push(&mut self, x: i32) {
self.items.push(x);
match self.min.last() {
Some(min) => {
if *min >= x {
self.min.push(x)
}
},
None => self.min.push(x)
}
}

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

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

fn min(&self) -> i32 {
*self.min.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();
*/
```

### **...**

```
Expand Down
55 changes: 55 additions & 0 deletions lcof/面试题30. 包含min函数的栈/Solution.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
struct MinStack {
items: Vec<i32>,
min: 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 {
MinStack {
items: Vec::new(),
min: Vec::new(),
}
}

fn push(&mut self, x: i32) {
self.items.push(x);
match self.min.last() {
Some(min) => {
if *min >= x {
self.min.push(x)
}
},
None => self.min.push(x)
}
}

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

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

fn min(&self) -> i32 {
*self.min.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();
*/