===================== 解題思路 =====================
基本也是先找 = 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>