如何在 php 中高效查找数字所在的区间
在 php 中,我们需要查找某个数字在给定的一系列区间中的位置。假设我们有一个待查找的数字 123,以及一系列用来计算区间的数组 [10, 20, 50, 100, 200, 500]。我们的目标是返回 100 或其在数组中的索引 3。
一个简单的方法是一一比较,但当数据量大时,这种方法效率低下。一种更优雅的解决方案是利用 php 的内置函数。
解决方案:
立即学习“PHP免费学习笔记(深入)”;
根据 $index 的值进行以下判断:
示例代码:
$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); // 输出:3
以上就是PHP中如何高效查找数字所属区间?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号