Fix the bug of index in rust codes (#685)

This commit is contained in:
Night Cruising 2023-08-14 00:54:15 +08:00 committed by GitHub
parent 0c18198c01
commit 5a4182372c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -8,16 +8,16 @@
fn binary_search(nums: &[i32], target: i32) -> i32 {
// 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
let mut i = 0;
let mut j = nums.len() - 1;
let mut j = nums.len() as i32 - 1;
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
while i <= j {
let m = i + (j - i) / 2; // 计算中点索引 m
if nums[m] < target { // 此情况说明 target 在区间 [m+1, j] 中
if nums[m as usize] < target { // 此情况说明 target 在区间 [m+1, j] 中
i = m + 1;
} else if nums[m] > target { // 此情况说明 target 在区间 [i, m-1] 中
} else if nums[m as usize] > target { // 此情况说明 target 在区间 [i, m-1] 中
j = m - 1;
} else { // 找到目标元素,返回其索引
return m as i32;
return m;
}
}
// 未找到目标元素,返回 -1
@ -28,16 +28,16 @@ fn binary_search(nums: &[i32], target: i32) -> i32 {
fn binary_search_lcro(nums: &[i32], target: i32) -> i32 {
// 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
let mut i = 0;
let mut j = nums.len();
let mut j = nums.len() as i32;
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
while i < j {
let m = i + (j - i) / 2; // 计算中点索引 m
if nums[m] < target { // 此情况说明 target 在区间 [m+1, j) 中
if nums[m as usize] < target { // 此情况说明 target 在区间 [m+1, j) 中
i = m + 1;
} else if nums[m] > target { // 此情况说明 target 在区间 [i, m) 中
} else if nums[m as usize] > target { // 此情况说明 target 在区间 [i, m) 中
j = m - 1;
} else { // 找到目标元素,返回其索引
return m as i32;
return m;
}
}
// 未找到目标元素,返回 -1