我需要在一个数组中找到离零最近的正数和负数。
- 如果数组是
空
的,我们将返回0
。 - 如果数组中有例如
-7, 7
,我们将返回7
。
这是正确的做法吗?
$ts = [1.7, 7, -10, 13, 8.4, -7.2, -12, -3.7, 3.5, -9.6, 6.5, -1.7, -6.2, 7];
function closestToZero (array $ts)
{
if(empty($ts)){
return 0;
}
$negativeArr = [];
$postiveValue = [];
foreach ($ts as $number) {
if ($number < 0) {
$negativeArr[] = $number;
}elseif ($number > 0 ) {
$postiveValue[] = $number;
}
}
if(!empty($negativeArr)){
$minnegative = max($negativeArr);
}
if (!empty($postiveValue)) {
$minPositive = min($postiveValue);
}
if ((abs($minnegative) - $minPositive) == 0) {
return $minPositive;
}else{
return $minnegative.' '.$minPositive;
}
}
echo "结果是 ".closestToZero($ts);
编辑:
实际上我在寻找一种更优化的方法来完成它,在做了一些研究后,我发现这个方法更加优化。
//if the array is empty we do nothing we return
if(empty($ts)){
return 0;
}else{
$referenceValue = 0;
//the trick is to add the reference value to the array if it doesnt exist
if (in_array($referenceValue, $ts) === FALSE) {
array_push($ts, $referenceValue);
}
//we sort the array in an ascending order
sort($ts);
// now we are able to get the nearest postive and negative values from 0
$referenceValueKey = array_search($referenceValue, $ts);
$positiveValueKey = $referenceValueKey + 1;
$negativeValueKey = $referenceValueKey - 1;
$result = '';
// if there is the same number as negative and positive in the array, we return the positive one
if((abs($ts[$negativeValueKey]) - $ts[$positiveValueKey]) == 0 )
{
$result.= $ts[$positiveValueKey];
}else{
$result.= $ts[$negativeValueKey].' '.$ts[$positiveValueKey];
}
return $result;
}
}