Skip to content

Commit 10af2bd

Browse files
author
alain
committed
修复二分法 Rust 示例错误
1 parent 253bddc commit 10af2bd

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

problems/0704.二分查找.md

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -501,39 +501,39 @@ func search(nums: [Int], target: Int) -> Int {
501501

502502
### **Rust:**
503503

504-
(版本一)左闭右开区间
504+
(版本一)左闭右闭区间
505505

506506
```rust
507507
use std::cmp::Ordering;
508508
impl Solution {
509509
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
510-
let (mut left, mut right) = (0, nums.len());
511-
while left < right {
510+
let (mut left, mut right) = (0_i32, nums.len() as i32 - 1);
511+
while left <= right {
512512
let mid = (right + left) / 2;
513-
match nums[mid].cmp(&target) {
513+
match nums[mid as usize].cmp(&target) {
514514
Ordering::Less => left = mid + 1,
515-
Ordering::Greater => right = mid,
516-
Ordering::Equal => return mid as i32,
515+
Ordering::Greater => right = mid - 1,
516+
Ordering::Equal => return mid,
517517
}
518518
}
519519
-1
520520
}
521521
}
522522
```
523523

524-
//(版本二)左闭右闭区间
524+
//(版本二)左闭右开区间
525525

526526
```rust
527527
use std::cmp::Ordering;
528528
impl Solution {
529529
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
530-
let (mut left, mut right) = (0, nums.len());
531-
while left <= right {
530+
let (mut left, mut right) = (0_i32, nums.len() as i32);
531+
while left < right {
532532
let mid = (right + left) / 2;
533-
match nums[mid].cmp(&target) {
533+
match nums[mid as usize].cmp(&target) {
534534
Ordering::Less => left = mid + 1,
535-
Ordering::Greater => right = mid - 1,
536-
Ordering::Equal => return mid as i32,
535+
Ordering::Greater => right = mid,
536+
Ordering::Equal => return mid,
537537
}
538538
}
539539
-1

0 commit comments

Comments
 (0)