mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-21 23:16:41 +08:00
Refactor the section of bianry search.
This commit is contained in:
@ -12,7 +12,7 @@ function binarySearch(nums: number[], target: number): number {
|
||||
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
|
||||
while (i <= j) {
|
||||
// 计算中点索引 m
|
||||
const m = Math.floor((i + j) / 2);
|
||||
const m = Math.floor(i + (j - i) / 2);
|
||||
if (nums[m] < target) {
|
||||
// 此情况说明 target 在区间 [m+1, j] 中
|
||||
i = m + 1;
|
||||
@ -35,7 +35,7 @@ function binarySearchLCRO(nums: number[], target: number): number {
|
||||
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
|
||||
while (i < j) {
|
||||
// 计算中点索引 m
|
||||
const m = Math.floor((i + j) / 2);
|
||||
const m = Math.floor(i + (j - i) / 2);
|
||||
if (nums[m] < target) {
|
||||
// 此情况说明 target 在区间 [m+1, j) 中
|
||||
i = m + 1;
|
||||
|
Reference in New Issue
Block a user