L459 Closest Number in Sorted Array
Given a target number and an integer array A sorted in ascending order, find the indexi
in A such that A[i] is closest to the given target.
Return -1 if there is no element in the array.
Notice
There can be duplicate elements in the array, and we can return any of the indices with same value.
Example
Given[1, 2, 3]
and target =2
, return1
.
Given[1, 4, 6]
and target =3
, return1
.
Given[1, 4, 6]
and target =5
, return1
or2
.
Given[1, 3, 3, 4]
and target =2
, return0
or1
or2
.
O(logn) time complexity.
in fact you can try finding the 1st number that is larger than target. (大于或等于?) then check A[1st] and A[1st - 1] which one is closer to target, then return
when return 1st lager than target, use this because target may not exist in array
if (A[start] >= target) { return start; } if (A[end] >= target) { return end; }
Last updated