mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
Merge pull request #2331 from fwqaaq/patch-1
Update 0704.二分查找.md about Rust
This commit is contained in:
@ -481,41 +481,39 @@ func search(nums: [Int], target: Int) -> Int {
|
||||
|
||||
### **Rust:**
|
||||
|
||||
```rust
|
||||
# (版本一)左闭右闭区间
|
||||
(版本一)左闭右开区间
|
||||
|
||||
```rust
|
||||
use std::cmp::Ordering;
|
||||
impl Solution {
|
||||
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
|
||||
let mut left:usize = 0;
|
||||
let mut right:usize = nums.len() - 1;
|
||||
while left as i32 <= right as i32{
|
||||
let mid = (left + right) / 2;
|
||||
if nums[mid] < target {
|
||||
left = mid + 1;
|
||||
} else if nums[mid] > target {
|
||||
right = mid - 1;
|
||||
} else {
|
||||
return mid as i32;
|
||||
let (mut left, mut right) = (0, nums.len());
|
||||
while left < right {
|
||||
let mid = (right + left) / 2;
|
||||
match nums[mid].cmp(&target) {
|
||||
Ordering::Less => left = mid + 1,
|
||||
Ordering::Greater => right = mid,
|
||||
Ordering::Equal => return mid as i32,
|
||||
}
|
||||
}
|
||||
-1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
# (版本二)左闭右开区间
|
||||
//(版本二)左闭右闭区间
|
||||
|
||||
```rust
|
||||
use std::cmp::Ordering;
|
||||
impl Solution {
|
||||
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
|
||||
let mut left:usize = 0;
|
||||
let mut right:usize = nums.len();
|
||||
while left < right {
|
||||
let mid = (left + right) / 2;
|
||||
if nums[mid] < target {
|
||||
left = mid + 1;
|
||||
} else if nums[mid] > target {
|
||||
right = mid;
|
||||
} else {
|
||||
return mid as i32;
|
||||
let (mut left, mut right) = (0, nums.len());
|
||||
while left <= right {
|
||||
let mid = (right + left) / 2;
|
||||
match nums[mid].cmp(&target) {
|
||||
Ordering::Less => left = mid + 1,
|
||||
Ordering::Greater => right = mid - 1,
|
||||
Ordering::Equal => return mid as i32,
|
||||
}
|
||||
}
|
||||
-1
|
||||
|
Reference in New Issue
Block a user