Skip to content

feat: add rust solution to lc problem: No.0075 #682

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 23, 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
35 changes: 35 additions & 0 deletions solution/0000-0099/0075.Sort Colors/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,41 @@ func sortColors(nums []int) {
}
```

### **Rust**

```rust
impl Solution {
pub fn sort_colors(nums: &mut Vec<i32>) {
let len = nums.len();
if len < 2 {
return;
}

let mut l = 0;
let mut r = len - 1;
let mut i = 0;
while i <= r {
match nums[i] {
0 => {
nums.swap(i, l);
l += 1;
i += 1;
}
2 => {
nums.swap(i, r);
// usize 不可为负数,会导致 Rust panic
match r {
0 => return,
_ => r -= 1,
}
}
_ => i += 1,
}
}
}
}
```

### **...**

```
Expand Down
34 changes: 34 additions & 0 deletions solution/0000-0099/0075.Sort Colors/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,40 @@ func sortColors(nums []int) {
}
```

### **Rust**

```rust
impl Solution {
pub fn sort_colors(nums: &mut Vec<i32>) {
let len = nums.len();
if len < 2 {
return;
}

let mut l = 0;
let mut r = len - 1;
let mut i = 0;
while i <= r {
match nums[i] {
0 => {
nums.swap(i, l);
l += 1;
i += 1;
}
2 => {
nums.swap(i, r);
match r {
0 => return,
_ => r -= 1,
}
}
_ => i += 1,
}
}
}
}
```

### **...**

```
Expand Down
29 changes: 29 additions & 0 deletions solution/0000-0099/0075.Sort Colors/Solution.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
impl Solution {
pub fn sort_colors(nums: &mut Vec<i32>) {
let len = nums.len();
if len < 2 {
return;
}

let mut l = 0;
let mut r = len - 1;
let mut i = 0;
while i <= r {
match nums[i] {
0 => {
nums.swap(i, l);
l += 1;
i += 1;
}
2 => {
nums.swap(i, r);
match r {
0 => return,
_ => r -= 1,
}
}
_ => i += 1,
}
}
}
}