If you are not going to execute several such queries in an array, there is no better way than checking the brute force linear time for each number.
If you make multiple queries in one array, first do a sort and then do a double search - this will reduce the time for such queries to O (log (n)), but you still pay O (n * log (n)) to sort , therefore it is reasonable if the number of requests is large enough, i.e. k * n β (much more) n * log (n) + k * log (n), where k is the number of requests.
If the array changes, create a binary search tree tree and run a query with a lower bound. This is again reasonable if the request for the nearest number is relatively large compared to requests for changing the array, as well as the number of elements. Since the cost of building the tree is O (n * log (n)), as well as the cost of updating is O (logn), you need to have k * log (n) + n * log (n) + k * log (n) < (much less) k * n
source share