
php:精准查找数组区间
当需要查找一个数值在给定区间数组中的位置时,直接逐一比较无疑过于低效。本文介绍一种更加优化的解决方法,利用 php 内置函数巧妙实现精准查找。
以下代码展示了这种方法的具体实现:
$arr = [10, 20, 50, 100, 200, 500];
function findIndex($arr, $num)
{
$arr[] = $num;
sort($arr);
$index = array_search($num, $arr);
$lastIndex = $index - 1;
$nextIndex = $index + 1;
if ($lastIndex < 0) {
return $index;
} elseif ($nextIndex >= count($arr)) {
return $index;
} else {
return $arr[$lastIndex] <= $arr[$index]
&& $arr[$index] < $arr[$nextIndex]
? $lastIndex
: $index;
}
}
$res = findIndex($arr, 123);
var_dump($res);该函数通过以下步骤实现区间查找:
立即学习“PHP免费学习笔记(深入)”;
这种方法在数据量较大的场景下具有较高的效率,相比于逐一比较,它无需重复对每个元素进行检查,避免了不必要的性能开销。
以上就是PHP数组区间查找:如何高效定位数值在已排序数组中的位置?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号