- Given a list of n integers sorted in ascending order, find the closest number (value) in the list to a given target number. How quickly can you do it?
I'm interested to know if there's any feedback for my code.
"""
def getClosestValue(arr, target): n = len(arr) left = 0 right = n - 1 mid = 0 # edge case if (target >= arr[n - 1]): return arr[n - 1] # BSearch solution: Time & Space: Log(N) while (left < right): mid = (left + right) // 2 # find the mid if (arr[mid] == target): return arr[mid] if (target < arr[mid]): # If target is greater than previous # to mid, return closest of two if (mid > 0 and target > arr[mid - 1]): return findClosest(arr[mid - 1], arr[mid], target) # update right right = mid else: if (mid < n - 1 and target < arr[mid + 1]): return findClosest(arr[mid], arr[mid + 1], target) # update i left = mid + 1 return arr[mid] # findClosest # We find the closest by taking the difference # between the target and both values. It assumes # that val2 is greater than val1 and target lies # between these two. def findClosest(val1, val2, target): if (target - val1 >= val2 - target): return val2 else: return val1 # Sample code arr = [1, 2, 3, 4, 5, 5, 8, 10] target = 7 print(getClosestValue(arr, target))