From ec23617a38b151890880b9d3deb659239442c916 Mon Sep 17 00:00:00 2001 From: YangFong <70502828+YangFong@users.noreply.github.com> Date: Sun, 23 Jan 2022 17:02:48 +0800 Subject: [PATCH] feat: add rust solution to lc problem: No.0075 No.0075.Sort Colors --- solution/0000-0099/0075.Sort Colors/README.md | 35 +++++++++++++++++++ .../0000-0099/0075.Sort Colors/README_EN.md | 34 ++++++++++++++++++ .../0000-0099/0075.Sort Colors/Solution.rs | 29 +++++++++++++++ 3 files changed, 98 insertions(+) create mode 100644 solution/0000-0099/0075.Sort Colors/Solution.rs diff --git a/solution/0000-0099/0075.Sort Colors/README.md b/solution/0000-0099/0075.Sort Colors/README.md index 95e52c35feb41..c98def6220a93 100644 --- a/solution/0000-0099/0075.Sort Colors/README.md +++ b/solution/0000-0099/0075.Sort Colors/README.md @@ -187,6 +187,41 @@ func sortColors(nums []int) { } ``` +### **Rust** + +```rust +impl Solution { + pub fn sort_colors(nums: &mut Vec) { + 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, + } + } + } +} +``` + ### **...** ``` diff --git a/solution/0000-0099/0075.Sort Colors/README_EN.md b/solution/0000-0099/0075.Sort Colors/README_EN.md index 313d3b725d7a4..8c1a277da3e0f 100644 --- a/solution/0000-0099/0075.Sort Colors/README_EN.md +++ b/solution/0000-0099/0075.Sort Colors/README_EN.md @@ -158,6 +158,40 @@ func sortColors(nums []int) { } ``` +### **Rust** + +```rust +impl Solution { + pub fn sort_colors(nums: &mut Vec) { + 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, + } + } + } +} +``` + ### **...** ``` diff --git a/solution/0000-0099/0075.Sort Colors/Solution.rs b/solution/0000-0099/0075.Sort Colors/Solution.rs new file mode 100644 index 0000000000000..06c739478f301 --- /dev/null +++ b/solution/0000-0099/0075.Sort Colors/Solution.rs @@ -0,0 +1,29 @@ +impl Solution { + pub fn sort_colors(nums: &mut Vec) { + 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, + } + } + } +}