2 回答

TA貢獻(xiàn)1794條經(jīng)驗 獲得超8個贊
您需要迭代數(shù)組并比較每個數(shù)字,然后保存數(shù)字(如果它比舊數(shù)字更接近您的針):
function precessorAndSuccessor(array $numbers, int $needle){
$pre = NULL;
$suc = NULL;
foreach($numbers as $number){
if($number < $needle){
if($pre === NULL || $pre < $number){
$pre = $number;
}
}elseif($number > $needle){
if($suc === NULL || $suc > $number){
$suc = $number;
}
}
}
return [
"predecessor" => $pre,
"successsor" => $suc
];
}
``

TA貢獻(xiàn)1797條經(jīng)驗 獲得超4個贊
如果對數(shù)組進(jìn)行排序,則只需運行并檢查:
$num = 7;
$pre = $suc = false;
sort($array);
foreach($array as $v) {
if($v < $num) { $pre = $v; }
if($v > $num) { $suc = $v; break; }
}
- 2 回答
- 0 關(guān)注
- 140 瀏覽
添加回答
舉報