如何在 php 中高效查找数字所在的区间
在 php 中,我们需要查找某个数字在给定的一系列区间中的位置。假设我们有一个待查找的数字 123,以及一系列用来计算区间的数组 [10, 20, 50, 100, 200, 500]。我们的目标是返回 100 或其在数组中的索引 3。
一个简单的方法是一一比较,但当数据量大时,这种方法效率低下。一种更优雅的解决方案是利用 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