From 75b7aa25a1c8e65917da2aab7ed819dab90afce2 Mon Sep 17 00:00:00 2001 From: Michael Xu <xzhseh@gmail.com> Date: Tue, 19 Sep 2023 15:46:08 -0400 Subject: [PATCH] feat: add rust solution to lc problem: No.0287 --- .../0287.Find the Duplicate Number/README.md | 27 +++++++++++++++++++ .../README_EN.md | 27 +++++++++++++++++++ .../Solution.rs | 22 +++++++++++++++ 3 files changed, 76 insertions(+) create mode 100644 solution/0200-0299/0287.Find the Duplicate Number/Solution.rs diff --git a/solution/0200-0299/0287.Find the Duplicate Number/README.md b/solution/0200-0299/0287.Find the Duplicate Number/README.md index 79e75b5c3693f..94a85be0d38d4 100644 --- a/solution/0200-0299/0287.Find the Duplicate Number/README.md +++ b/solution/0200-0299/0287.Find the Duplicate Number/README.md @@ -126,6 +126,33 @@ public: }; ``` +### **Rust** + +```rust +impl Solution { + #[allow(dead_code)] + pub fn find_duplicate(nums: Vec<i32>) -> i32 { + let mut left = 0; + let mut right = nums.len() - 1; + + while left < right { + let mid = (left + right) >> 1; + let cnt = nums + .iter() + .filter(|x| **x <= mid as i32) + .count(); + if cnt > mid { + right = mid; + } else { + left = mid + 1; + } + } + + left as i32 + } +} +``` + ### **Go** ```go diff --git a/solution/0200-0299/0287.Find the Duplicate Number/README_EN.md b/solution/0200-0299/0287.Find the Duplicate Number/README_EN.md index 7aff606b48e27..9b616b978e6fa 100644 --- a/solution/0200-0299/0287.Find the Duplicate Number/README_EN.md +++ b/solution/0200-0299/0287.Find the Duplicate Number/README_EN.md @@ -107,6 +107,33 @@ public: }; ``` +### **Rust** + +```rust +impl Solution { + #[allow(dead_code)] + pub fn find_duplicate(nums: Vec<i32>) -> i32 { + let mut left = 0; + let mut right = nums.len() - 1; + + while left < right { + let mid = (left + right) >> 1; + let cnt = nums + .iter() + .filter(|x| **x <= mid as i32) + .count(); + if cnt > mid { + right = mid; + } else { + left = mid + 1; + } + } + + left as i32 + } +} +``` + ### **Go** ```go diff --git a/solution/0200-0299/0287.Find the Duplicate Number/Solution.rs b/solution/0200-0299/0287.Find the Duplicate Number/Solution.rs new file mode 100644 index 0000000000000..cd59c27fa1df6 --- /dev/null +++ b/solution/0200-0299/0287.Find the Duplicate Number/Solution.rs @@ -0,0 +1,22 @@ +impl Solution { + #[allow(dead_code)] + pub fn find_duplicate(nums: Vec<i32>) -> i32 { + let mut left = 0; + let mut right = nums.len() - 1; + + while left < right { + let mid = (left + right) >> 1; + let cnt = nums + .iter() + .filter(|x| **x <= mid as i32) + .count(); + if cnt > mid { + right = mid; + } else { + left = mid + 1; + } + } + + left as i32 + } +} \ No newline at end of file