mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #665 from andywang0607/704_rust
增加0704.二分查找 Rust語言實現
This commit is contained in:
@ -406,6 +406,49 @@ func search(nums: [Int], target: Int) -> Int {
|
||||
|
||||
```
|
||||
|
||||
**Rust:**
|
||||
|
||||
```rust
|
||||
# (版本一)左闭右闭区间
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
-1
|
||||
}
|
||||
}
|
||||
|
||||
# (版本二)左闭右开区间
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
-1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
|
Reference in New Issue
Block a user