Closest Number in Sorted Array
Posted codingEskimo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Closest Number in Sorted Array相关的知识,希望对你有一定的参考价值。
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 start = 0; int end = A.length - 1; while(start + 1 < end) { int mid = start + (end - start) / 2; if (A[mid] == target) { return mid; } else if (A[mid] < target) { start = mid; } else { end = mid; } } int startDis = Math.abs(A[start] - target); int endDis = Math.abs(A[end] - target); return startDis < endDis? start : end; } }
O(logN)
以上是关于Closest Number in Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章
[LintCode] 459 Closest Number in Sorted Array
lintcode459- Closest Number in Sorted Array- easy
Closest In Sorted Array - Medium