Closest Number in Sorted Array

Closest Number in Sorted Array_第1张图片
Closest Number in Sorted Array.png

===================== 解題思路 =====================

基本也是先找 = target 為主的資料 如果找到可直接回傳 接下來就是檢查左右兩個 index 裡的對應數值跟 target 的絕對值差距(距離)

===================== C++ code ====================


lass Solution {

public:

/**
 * @param A an integer array sorted in ascending order
 * @param target an integer
 * @return an integer
 */
int closestNumber(vector& A, int target) {
    // Write your code here
    if(A.size() == 0) return -1;
    int left = 0, right = A.size() -1;
    while(left + 1 < right)
    {
        int mid = left + (right - left) / 2;
        if(A[mid] >= target) right = mid;
        else left = mid;
    }
    return abs(A[left] - target) < abs(A[right] - target)? left : right;  
}

};

你可能感兴趣的:(Closest Number in Sorted Array)