mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
@ -501,19 +501,19 @@ func search(nums: [Int], target: Int) -> Int {
|
|||||||
|
|
||||||
### **Rust:**
|
### **Rust:**
|
||||||
|
|
||||||
(版本一)左闭右开区间
|
(版本一)左闭右闭区间
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
use std::cmp::Ordering;
|
use std::cmp::Ordering;
|
||||||
impl Solution {
|
impl Solution {
|
||||||
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
|
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
|
||||||
let (mut left, mut right) = (0, nums.len());
|
let (mut left, mut right) = (0_i32, nums.len() as i32 - 1);
|
||||||
while left < right {
|
while left <= right {
|
||||||
let mid = (right + left) / 2;
|
let mid = (right + left) / 2;
|
||||||
match nums[mid].cmp(&target) {
|
match nums[mid as usize].cmp(&target) {
|
||||||
Ordering::Less => left = mid + 1,
|
Ordering::Less => left = mid + 1,
|
||||||
Ordering::Greater => right = mid,
|
Ordering::Greater => right = mid - 1,
|
||||||
Ordering::Equal => return mid as i32,
|
Ordering::Equal => return mid,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
-1
|
-1
|
||||||
@ -521,19 +521,19 @@ impl Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
//(版本二)左闭右闭区间
|
//(版本二)左闭右开区间
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
use std::cmp::Ordering;
|
use std::cmp::Ordering;
|
||||||
impl Solution {
|
impl Solution {
|
||||||
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
|
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
|
||||||
let (mut left, mut right) = (0, nums.len());
|
let (mut left, mut right) = (0_i32, nums.len() as i32);
|
||||||
while left <= right {
|
while left < right {
|
||||||
let mid = (right + left) / 2;
|
let mid = (right + left) / 2;
|
||||||
match nums[mid].cmp(&target) {
|
match nums[mid as usize].cmp(&target) {
|
||||||
Ordering::Less => left = mid + 1,
|
Ordering::Less => left = mid + 1,
|
||||||
Ordering::Greater => right = mid - 1,
|
Ordering::Greater => right = mid,
|
||||||
Ordering::Equal => return mid as i32,
|
Ordering::Equal => return mid,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
-1
|
-1
|
||||||
|
Reference in New Issue
Block a user