问题:有一个数组$nums = [1,2,5,7,7,8,8,8,9,10,13]; $target = 8; 返回对应的下标[5,6],找不到返回[-1,-1]
要在 PHP 中实现二分查找并返回目标元素的所有下标,我们需要对基本的二分查找算法进行一些修改。基本的二分查找只返回目标元素的单个下标,但在这里我们需要找到所有匹配的下标。
//php循环
<?php
function binarySearchIndices($nums, $target) {
$left = 0;
$right = count($nums) - 1;
$indices = [];
while ($left <= $right) {
$mid = $left + floor(($right - $left) / 2);
if ($nums[$mid] == $target) {
// 找到一个匹配,继续向左和向右查找其他可能的匹配
$indices[] = $mid;
$tempLeft = $mid - 1;
$tempRight = $mid + 1;
// 向左查找其他匹配
while ($tempLeft >= 0 && $nums[$tempLeft] == $target) {
$indices[] = $tempLeft;
$tempLeft--;
}
// 向右查找其他匹配
while ($tempRight < count($nums) && $nums[$tempRight] == $target) {
$indices[] = $tempRight;
$tempRight++;
}
// 返回所有匹配的下标
return $indices;
} elseif ($nums[$mid] < $target) {
$left = $mid + 1;
} else {
$right = $mid - 1;
}
}
// 如果没有找到,返回 [-1, -1]
return [-1, -1];
}
$nums = [1,2,5,7,7,8,8,9,10,13];
$target = 8;
$result = binarySearchIndices($nums, $target);
print_r($result);
?>
这个函数首先使用标准的二分查找找到目标元素的一个匹配。然后,它向左和向右扩展查找,直到找到所有匹配的下标。如果没有找到任何匹配,它会返回 [-1, -1]。
运行上述代码,对于 $nums = [1,2,5,7,7,8,8,9,10,13] 和 $target = 8,输出将是:
Array
(
[0] => 5
[1] => 6
)
这表示目标元素 8 在数组中的下标是 5 和 6。
//php递归
function binarySearchIndicesRecursive($nums, $target, $left = 0, $right = null) {
if ($right === null) {
$right = count($nums) - 1;
}
$indices = [];
if ($left > $right) {
return $indices;
}
$mid = $left + floor(($right - $left) / 2);
if ($nums[$mid] == $target) {
// 找到一个匹配,将其下标加入结果数组
$indices[] = $mid;
// 递归地在左半部分和右半部分继续查找
$indices = array_merge(
$indices,
binarySearchIndicesRecursive($nums, $target, $left, $mid - 1),
binarySearchIndicesRecursive($nums, $target, $mid + 1, $right)
);
} elseif ($nums[$mid] < $target) {
// 如果目标值大于中间值,则在右半部分继续查找
$indices = binarySearchIndicesRecursive($nums, $target, $mid + 1, $right);
} else {
// 如果目标值小于中间值,则在左半部分继续查找
$indices = binarySearchIndicesRecursive($nums, $target, $left, $mid - 1);
}
return $indices;
}
$nums = [1,2,5,7,7,8,8,9,10,13];
$target = 8;
$result = binarySearchIndicesRecursive($nums, $target);
print_r($result);