【发布时间】:2012-04-27 03:47:47
【问题描述】:
我在 php 中有一个关联数组。键是整数。如何找到与任何整数输入最近的键?
【问题讨论】:
-
当有两个最近的键时会发生什么。
-
没有考虑到这一点。需要弄清楚。
我在 php 中有一个关联数组。键是整数。如何找到与任何整数输入最近的键?
【问题讨论】:
一个简单但蛮力的方法:
$distance = 1000000; // initialize distance as "far away"
foreach ($array as $idx => $value)
if (abs ($idx - $target_index) < $distance)
{
$distance = abs ($idx - $target_index);
$best_idx = $idx;
}
【讨论】:
如果数组键是有序的,您可以使用更有效的算法(这可能会或可能不会产生明显的差异,具体取决于它的用途和数组的大小):
$arr = [2 => 'a', 4 => 'b', 7 => 'c'];
$input = 5;
if (isset($arr[$input])) {
return $input;
}
foreach ($arr as $key => $value) {
if ($key > $input) {
if (prev($arr) === FALSE) {
// If the input is smaller than the first key
return $key;
}
$prevKey = key($arr);
if (abs($key - $input) < abs($prevKey - $input)) {
return $key;
} else {
return $prevKey;
}
}
【讨论】: