This commit is contained in:
krahets
2023-04-17 21:57:42 +08:00
parent b472215f0e
commit cf4a59e3d6
20 changed files with 247 additions and 198 deletions

View File

@@ -135,16 +135,19 @@ $$
/* 二分查找(双闭区间) */
function binarySearch(nums, target) {
// 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
let i = 0, j = nums.length - 1;
let i = 0,
j = nums.length - 1;
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
while (i <= j) {
const m = parseInt((i + j) / 2); // 计算中点索引 m 在 JS 中需使用 parseInt 函数取整
if (nums[m] < target) // 此情况说明 target 在区间 [m+1, j] 中
// 计算中点索引 m ,使用 parseInt() 向下取整
const m = parseInt((i + j) / 2);
if (nums[m] < target)
// 此情况说明 target 在区间 [m+1, j] 中
i = m + 1;
else if (nums[m] > target) // 此情况说明 target 在区间 [i, m-1] 中
else if (nums[m] > target)
// 此情况说明 target 在区间 [i, m-1] 中
j = m - 1;
else
return m; // 找到目标元素,返回其索引
else return m; // 找到目标元素,返回其索引
}
// 未找到目标元素,返回 -1
return -1;
@@ -157,15 +160,20 @@ $$
/* 二分查找(双闭区间) */
function binarySearch(nums: number[], target: number): number {
// 初始化双闭区间 [0, n-1] ,即 i, j 分别指向数组首元素、尾元素
let i = 0, j = nums.length - 1;
let i = 0,
j = nums.length - 1;
// 循环,当搜索区间为空时跳出(当 i > j 时为空)
while (i <= j) {
const m = Math.floor((i + j) / 2); // 计算中点索引 m
if (nums[m] < target) { // 此情况说明 target 在区间 [m+1, j] 中
// 计算中点索引 m
const m = Math.floor((i + j) / 2);
if (nums[m] < target) {
// 此情况说明 target 在区间 [m+1, j] 中
i = m + 1;
} else if (nums[m] > target) { // 此情况说明 target 在区间 [i, m-1] 中
} else if (nums[m] > target) {
// 此情况说明 target 在区间 [i, m-1] 中
j = m - 1;
} else { // 找到目标元素,返回其索引
} else {
// 找到目标元素,返回其索引
return m;
}
}
@@ -431,16 +439,20 @@ $$
/* 二分查找(左闭右开) */
function binarySearch1(nums, target) {
// 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
let i = 0, j = nums.length;
let i = 0,
j = nums.length;
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
while (i < j) {
const m = parseInt((i + j) / 2); // 计算中点索引 m 在 JS 中需使用 parseInt 函数取整
if (nums[m] < target) // 此情况说明 target 在区间 [m+1, j) 中
// 计算中点索引 m ,使用 parseInt() 向下取整
const m = parseInt((i + j) / 2);
if (nums[m] < target)
// 此情况说明 target 在区间 [m+1, j) 中
i = m + 1;
else if (nums[m] > target) // 此情况说明 target 在区间 [i, m) 中
else if (nums[m] > target)
// 此情况说明 target 在区间 [i, m) 中
j = m;
else // 找到目标元素,返回其索引
return m;
// 找到目标元素,返回其索引
else return m;
}
// 未找到目标元素,返回 -1
return -1;
@@ -453,15 +465,20 @@ $$
/* 二分查找(左闭右开) */
function binarySearch1(nums: number[], target: number): number {
// 初始化左闭右开 [0, n) ,即 i, j 分别指向数组首元素、尾元素+1
let i = 0, j = nums.length;
let i = 0,
j = nums.length;
// 循环,当搜索区间为空时跳出(当 i = j 时为空)
while (i < j) {
const m = Math.floor((i + j) / 2); // 计算中点索引 m
if (nums[m] < target) { // 此情况说明 target 在区间 [m+1, j) 中
// 计算中点索引 m
const m = Math.floor((i + j) / 2);
if (nums[m] < target) {
// 此情况说明 target 在区间 [m+1, j) 中
i = m + 1;
} else if (nums[m] > target) { // 此情况说明 target 在区间 [i, m) 中
} else if (nums[m] > target) {
// 此情况说明 target 在区间 [i, m) 中
j = m;
} else { // 找到目标元素,返回其索引
} else {
// 找到目标元素,返回其索引
return m;
}
}