算法-在数组中获取制定值的索引值-php(二分法)
算法-在数组中获取制定值的索引值-php(二分法)
<?php
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @param target int整型
* @return int整型
*/
function search( $nums , $target )
{
// write code here
if (count($nums) == 0) {
return -1;
}
$leftIndex = 0;
$rightIndex = count($nums) - 1;
// 只要下标一直是左边<=右边,就需要一直找
while ($leftIndex <= $rightIndex){
// 中间元素的索引
$midIndex = floor(($leftIndex + $rightIndex) / 2);
// 如果中间索引对应的值等于目标值
if ($nums[$midIndex] == $target) {
return $midIndex;
}
// 比较找到的值和目标值
if ($nums[$midIndex] > $target) {
$rightIndex = $midIndex - 1;
} else {
$leftIndex = $midIndex + 1;
}
}
return -1;
}
本文来自博客园,作者:alisleepy,转载请注明原文链接:https://www.cnblogs.com/alisleepy/p/18667349

浙公网安备 33010602011771号