[Classic Interview Questions] minimum absolute value element and absolute value element in the sorting Array
[Question]
Subject: There is an sorted array (ascending). The array may have positive numbers, negative numbers, or 0. It is required to obtain the minimum absolute value of the elements in the array, the sequential comparison method is not supported (the complexity must be less than O (n) and can be implemented in any language. For example, for an array {-20,-13,-4, 6, 77,200}, the minimum absolute value is-4. |
[Analysis]
The given array is sorted in ascending order without repeating elements.
A simple idea is to traverse the array at a time and find the minimum value of the absolute value of the elements in the array. the time complexity is O (n ).
However, this wastes a condition of the question: the array is sorted. Therefore, you need to convert the original question. Considering the order of arrays, binary search is used.
Evaluate the element with the smallest absolute value in the array, and the smaller the absolute value closest to 0. Design Code based on this principle.
There are three situations:
(1) If all values are positive numbers, the first element value is returned. If (A [0]> = 0)
(2) If all values are negative, return the value of the last element. If (A [n-1] <= 0)
(3) If there is positive or negative, use the binary search to find the insert position of 0. If the position of 0 is found, 0 is the element with the smallest absolute value,
If 0 is not found, the left and right elements at the insert position are relatively absolute values, and a smaller value is returned. OK.
[Code]
/********************************** Date: * Author: SJF0115 * Title: Minimum Absolute Value element in sorting array * Source: Baidu * blog: * *********************************/# include <iostream> # include <algorithm> using namespace std; int MinAbs (int A [], int n) {if (n = 1) {return A [0];} // if // only positive if (A [0]> = 0) {return A [0];} // only negative if (A [n-1] <= 0) {return A [n-1] ;}// locate the 0 insert position int target = 0; int left = 0, right = n-1; int mid; while (left <= right) {mid = left + (right-left)/2; // The intermediate element equals to the target if (A [mid] = target) {return A [mid];} // the target is in the left half of the else if (A [mid]> target) {right = mid-1 ;} // target in the right half of the else {left = mid + 1 ;}/// while // the smallest absolute value if (abs (A [left]) <abs (A [right]) {return A [left];} return A [right];} int main () {// int A [] = {-6, -5,-4,-3,-2,-1}; // int A [] = {-6,-5,-4, 1, 2, 3 }; // int A [] = {77,200,}; int A [] = {-20,-13,-,}; int n = 6; cout <MinAbs (A, n) <endl; return 0 ;}