Skip to content

Commit 93e15c2

Browse files
committed
feat: add rust solution to lc problem: No.0704
No.0704.Binary Search
1 parent 5363891 commit 93e15c2

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

solution/0700-0799/0704.Binary Search/README.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,55 @@ var search = function (nums, target) {
138138
};
139139
```
140140

141+
### **Rust**
142+
143+
循环:
144+
145+
```rust
146+
use std::cmp::Ordering;
147+
148+
impl Solution {
149+
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
150+
let mut l = 0;
151+
let mut r = nums.len();
152+
while l < r {
153+
let mid = l + r >> 1;
154+
match nums[mid].cmp(&target) {
155+
Ordering::Less => l = mid + 1,
156+
Ordering::Greater => r = mid,
157+
Ordering::Equal => return mid as i32,
158+
}
159+
}
160+
-1
161+
}
162+
}
163+
```
164+
165+
递归:
166+
167+
```rust
168+
use std::cmp::Ordering;
169+
170+
impl Solution {
171+
fn binary_search(nums: Vec<i32>, target: i32, l: usize, r: usize) -> i32 {
172+
if l == r {
173+
return if nums[l] == target { l as i32 } else { -1 };
174+
}
175+
let mid = l + r >> 1;
176+
match nums[mid].cmp(&target) {
177+
Ordering::Less => Self::binary_search(nums, target, mid + 1, r),
178+
Ordering::Greater => Self::binary_search(nums, target, l, mid),
179+
Ordering::Equal => mid as i32,
180+
}
181+
}
182+
183+
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
184+
let r = nums.len() - 1;
185+
Self::binary_search(nums, target, 0, r)
186+
}
187+
}
188+
```
189+
141190
### **...**
142191

143192
```
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
use std::cmp::Ordering;
2+
3+
impl Solution {
4+
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
5+
let mut l = 0;
6+
let mut r = nums.len();
7+
while l < r {
8+
let mid = l + r >> 1;
9+
match nums[mid].cmp(&target) {
10+
Ordering::Less => l = mid + 1,
11+
Ordering::Greater => r = mid,
12+
Ordering::Equal => return mid as i32,
13+
}
14+
}
15+
-1
16+
}
17+
}

0 commit comments

Comments
 (0)