首页 > 代码库 > Closest Number in Sorted Array
Closest Number in Sorted Array
Given a target number and an integer array A sorted in ascending order, find the index i
in A such that A[i] is closest to the given target.
Return -1 if there is no element in the array.
分析
使用binary Search 找到可以插入 target 的 position, 例如是 i, 那么,从i(包括i)到后面,都是大于等于target的数字
1 如果 i == 0, return i,因为A[i]一定是最接近 target的数字,后面的数字都大于A[i]
2 如果 i > =,那么需要考虑A[i] 和 A[i - 1] 哪个更接近 target,就返回哪一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public class Solution { /** * @param A an integer array sorted in ascending order * @param target an integer * @return an integer */ public int closestNumber( int [] A, int target) { // Write your code here if (A == null || A.length == 0 ) return - 1 ; int left = 0 , right = A.length - 1 , mid; while (left < right){ mid = left + (right - left) / 2 ; if (A[mid] < target){ left = mid + 1 ; } else { right = mid; } } // when left == right, this is the first position that target can be insert if (right > 0 && (A[right] - target) > (target - A[right - 1 ])) return right - 1 ; else return right; } } |
null
Closest Number in Sorted Array
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。