美文网首页
Closest Number in Sorted Array

Closest Number in Sorted Array

作者: 一枚煎餅 | 来源:发表于2016-09-14 07:13 被阅读0次
Closest Number in Sorted Array.png

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

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

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

<pre><code>
lass Solution {

public:

/**
 * @param A an integer array sorted in ascending order
 * @param target an integer
 * @return an integer
 */
int closestNumber(vector<int>& 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;  
}

};
<code><pre>

相关文章

网友评论

      本文标题:Closest Number in Sorted Array

      本文链接:https://www.haomeiwen.com/subject/jmkvettx.html