Skip to content

Commit 801a22e

Browse files
authored
feat: add rust solution to lc problem: No.0075 (doocs#682)
No.0075.Sort Colors
1 parent bf4f9cd commit 801a22e

File tree

3 files changed

+98
-0
lines changed

3 files changed

+98
-0
lines changed

solution/0000-0099/0075.Sort Colors/README.md

+35
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,41 @@ func sortColors(nums []int) {
187187
}
188188
```
189189

190+
### **Rust**
191+
192+
```rust
193+
impl Solution {
194+
pub fn sort_colors(nums: &mut Vec<i32>) {
195+
let len = nums.len();
196+
if len < 2 {
197+
return;
198+
}
199+
200+
let mut l = 0;
201+
let mut r = len - 1;
202+
let mut i = 0;
203+
while i <= r {
204+
match nums[i] {
205+
0 => {
206+
nums.swap(i, l);
207+
l += 1;
208+
i += 1;
209+
}
210+
2 => {
211+
nums.swap(i, r);
212+
// usize 不可为负数,会导致 Rust panic
213+
match r {
214+
0 => return,
215+
_ => r -= 1,
216+
}
217+
}
218+
_ => i += 1,
219+
}
220+
}
221+
}
222+
}
223+
```
224+
190225
### **...**
191226

192227
```

solution/0000-0099/0075.Sort Colors/README_EN.md

+34
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,40 @@ func sortColors(nums []int) {
158158
}
159159
```
160160

161+
### **Rust**
162+
163+
```rust
164+
impl Solution {
165+
pub fn sort_colors(nums: &mut Vec<i32>) {
166+
let len = nums.len();
167+
if len < 2 {
168+
return;
169+
}
170+
171+
let mut l = 0;
172+
let mut r = len - 1;
173+
let mut i = 0;
174+
while i <= r {
175+
match nums[i] {
176+
0 => {
177+
nums.swap(i, l);
178+
l += 1;
179+
i += 1;
180+
}
181+
2 => {
182+
nums.swap(i, r);
183+
match r {
184+
0 => return,
185+
_ => r -= 1,
186+
}
187+
}
188+
_ => i += 1,
189+
}
190+
}
191+
}
192+
}
193+
```
194+
161195
### **...**
162196

163197
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
impl Solution {
2+
pub fn sort_colors(nums: &mut Vec<i32>) {
3+
let len = nums.len();
4+
if len < 2 {
5+
return;
6+
}
7+
8+
let mut l = 0;
9+
let mut r = len - 1;
10+
let mut i = 0;
11+
while i <= r {
12+
match nums[i] {
13+
0 => {
14+
nums.swap(i, l);
15+
l += 1;
16+
i += 1;
17+
}
18+
2 => {
19+
nums.swap(i, r);
20+
match r {
21+
0 => return,
22+
_ => r -= 1,
23+
}
24+
}
25+
_ => i += 1,
26+
}
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)