Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4134c34

Browse files
authored
Update 0704.二分查找.md about Rust
1 parent 8adede9 commit 4134c34

File tree

1 file changed

+19
-23
lines changed

1 file changed

+19
-23
lines changed

‎problems/0704.二分查找.md‎

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -481,41 +481,37 @@ func search(nums: [Int], target: Int) -> Int {
481481

482482
### **Rust:**
483483

484-
```rust
485-
# (版本一)左闭右闭区间
484+
(版本一)左闭右开区间
486485

486+
```rust
487487
impl Solution {
488488
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
489-
let mut left:usize = 0;
490-
let mut right:usize = nums.len() - 1;
491-
while left as i32 <= right as i32{
492-
let mid = (left + right) / 2;
493-
if nums[mid] < target {
494-
left = mid + 1;
495-
} else if nums[mid] > target {
496-
right = mid - 1;
497-
} else {
498-
return mid as i32;
489+
let (mut left, mut right) = (0, nums.len());
490+
while left < right {
491+
let mid = (right + left) / 2;
492+
match nums[mid].cmp(&target) {
493+
Ordering::Less => left = mid + 1,
494+
Ordering::Greater => right = mid,
495+
Ordering::Equal => return mid as i32,
499496
}
500497
}
501498
-1
502499
}
503500
}
501+
```
504502

505-
# (版本二)左闭右开区间
503+
//(版本二)左闭右闭区间
506504

505+
```rust
507506
impl Solution {
508507
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
509-
let mut left:usize = 0;
510-
let mut right:usize = nums.len();
511-
while left < right {
512-
let mid = (left + right) / 2;
513-
if nums[mid] < target {
514-
left = mid + 1;
515-
} else if nums[mid] > target {
516-
right = mid;
517-
} else {
518-
return mid as i32;
508+
let (mut left, mut right) = (0, nums.len());
509+
while left <= right {
510+
let mid = (right + left) / 2;
511+
match nums[mid].cmp(&target) {
512+
Ordering::Less => left = mid + 1,
513+
Ordering::Greater => right = mid - 1,
514+
Ordering::Equal => return mid as i32,
519515
}
520516
}
521517
-1

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /