Given a target integer T and an integer array A sorted in ascending order, find the index i in A such that A[i] is closest to T.
Assumptions:
There can be duplicate elements in the array, and we can return any of the indices with same value.
Examples:
A = {1, 2, 3}, T = 2, return 1
A = {1, 4, 6}, T = 3, return 1
A = {1, 4, 6}, T = 5, return 1 or 2
A = {1, 3, 3, 4}, T = 2, return 0 or 1 or 2
def find_closest_num(nums,target):
if len(nums) == 0:
return -1
left = 0
right = len(nums) - 1
while left < right - 1:
mid = (left + right)/2
if nums[mid] > target:
right = mid
elif nums[mid] < target:
left = mid
else:
return mid
return left if abs(nums[left] - target) < abs(nums[right] - target) else right
网友评论