http://www.lintcode.com/en/problem/closest-number-in-sorted-array/\#

standard binary search. if none of the start or end equals then compares the abs of the difference with target

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;

        int lastLess = 0;
        int firstGreat = 0;

        //get the last less than
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (A[mid] > target) {
                end = mid;
            } else if (A[mid] == target) {
                end = mid;
            } else {
                start = mid;
            }
        }

        if (A[end] <= target) {
            return end;
        }

        if (A[start] >= target) {
            return start;
        }

        return Math.abs(A[start] - target) < Math.abs(A[end] - target) ? start : end;

    }

results matching ""

    No results matching ""