Find Closest Number in a Sorted Array
Last updated
Last updated
Given a target integer and a sorted integer array, return the index that has the closest value to the target.
Does the array have both positive and negative number? Yes. Does the array contain duplicates? Yes. What if two numbers have the same difference? return any index
Scan the array keep a difference value. Terminate the search once the defference is increasing.
Linear time O(n)
The array is sorted. We can use an O(1) check to prune half of the search place. This is the only way to beat a linear solution.
O(1) check 3 cases
A[mid] > target: prune right section, search left section
A[mid] == target: return mid
A[mid] < target: prune left section, search right section
Simple recrusion can be implemented with while loop. Logarithmic time with constant space.