Tuesday, March 7, 2017

[LintCode] 459 Closest Number in Sorted Array 解题报告

Description
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.

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, return 1.

Given [1, 4, 6] and target = 3, return 1.

Given [1, 4, 6] and target = 5, return 1 or 2.

Given [1, 3, 3, 4] and target = 2, return 0 or 1 or 2.



Challenge
O(logn) time complexity.



思路
如果target比A[0]小或者比A[A.length - 1]大。那么我们直接知道closest是0或者A.length - 1。
剩下的情况二分法。找第一个>=target的index。
找到以后判断一下A[index] - target和target - A[index - 1],哪个小说明哪个离target近。



Code
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 0;
        }
        
        if (target <= A[0]) {
            return 0;
        }
        
        if (target >= A[A.length - 1]) {
            return A.length - 1;
        }
        
        // find first element >= target;
        int start = 0; 
        int end = A.length - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (A[mid] >= target) {
                end = mid;
            }
            else {
                start = mid;
            }
        }
        
        int index = end;
        if (A[start] >= target) {
            index = start;
        }
        
        return A[index] - target < target - A[index - 1] ? index : index - 1; 
    }
}