Problem:
An ordered array, the value may have negative values, or there may not be, you need to find out the absolute value of the least.
Method 1:
Iterate through the array, find the absolute value minimum, the time complexity O (n), and N is the number of elements.
Method 2:
Binary lookup, because the array is ordered, can be used to find the two points, time complexity O (logn).
Analysis steps:
- If the first number is positive, it indicates that the entire array has no negative numbers and returns the first number directly
- If the last number is negative, it indicates that the entire array has no positive number and returns the last digit directly.
- The elements of the array have positive negative values, and the element with the smallest absolute value must be at a positive negative junction, requiring two points to be found:
- If a[mid]<0, because the array is ascending, indicating that the minimum number of absolute values does not appear on the left side of A[mid], while judging the positive and negative of the a[mid+1] element, if it is negative, then the mid right interval needs to be searched, if a[mid-1] is not negative, Then the two numbers are the positive and negative junction points in the array, returning the absolute value of the two numbers is smaller.
- If a[mid]>0, because the array is ascending, indicating that the minimum number of absolute values does not appear on the right side of A[mid], while judging the positive and negative of the a[mid-1] element, if it is negative, then the two number is the positive and negative junction in the array, and returns the absolute value of these two numbers smaller if a[mid-1 ] is not negative, then you need to find the mid-left interval.
- If a[mid] = = 0, then A[mid] is absolutely the smallest element.
functionSelectabsminnum (Array $arr){ $start= 0; $len=Count($arr)-1; if($arr[0] > 0) {//Positive Array return $arr[0]; } if($arr[$len] < 0) {//Negative Array return $arr[$len]; } while($start<$len) { $mid= Floor(($start+$len)/2); if($arr[$mid] > 0) { if($arr[$mid-1] > 0) { $len=$mid-1; } Else { return min($arr[$mid], -$arr[$mid-1]); } } ElseIf($arr[$mid] < 0) { if($arr[$mid+ 1] < 0) { $start=$mid+ 1; } Else { return min(-$arr[$mid],$arr[$mid+ 1]); } } Else { return $arr[$mid]; } }}$SORTARR= [-5,-4,-4,-4, 5, 7, 9];EchoSelectabsminnum ($SORTARR),Php_eol;
Find the smallest number of absolute values in an ordered array