在给定整数值的给定数组中查找给定整数的后继者和前任者

假设我有一个这样的数组:

[12,3,4,5,8,9,11,20]

给定数字 7,那么数组中的前任/后继将是 5/8 如何有效地找到这些数字?

目前我的解决方案只是通过比较来寻找继任者。


墨色风雨
浏览 101回答 2
2回答

慕田峪9158850

您需要迭代数组并比较每个数字,然后保存数字(如果它比旧数字更接近您的针):function precessorAndSuccessor(array $numbers, int $needle){&nbsp; &nbsp; $pre = NULL;&nbsp; &nbsp; $suc = NULL;&nbsp; &nbsp; foreach($numbers as $number){&nbsp; &nbsp; &nbsp; &nbsp; if($number < $needle){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if($pre === NULL || $pre < $number){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $pre = $number;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }elseif($number > $needle){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if($suc === NULL || $suc > $number){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $suc = $number;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return [&nbsp; &nbsp; &nbsp; &nbsp; "predecessor" => $pre,&nbsp; &nbsp; &nbsp; &nbsp; "successsor" => $suc&nbsp; &nbsp; ];}``

繁星coding

如果对数组进行排序,则只需运行并检查:$num = 7;$pre = $suc = false;sort($array);foreach($array as $v) {&nbsp; &nbsp; if($v < $num) { $pre = $v; }&nbsp; &nbsp; if($v > $num) { $suc = $v; break; }}
打开App,查看更多内容
随时随地看视频慕课网APP