LintCode "The Smallest Difference"

时间:2022-09-22 15:24:07

Binary search.

class Solution {
int _findClosest(vector<int> &A, int v)
{
int s = , e = A.size() - ;
int ret = INT_MAX;
while(s <= e)
{
int mid = (s + e) / ;
int vmid = A[mid];
int dist = abs(vmid - v);
ret = min(ret, dist); if(vmid == v) return ;
if(vmid < v)
{
s = mid + ;
}
else if(vmid > v)
{
e = mid - ;
}
}
return ret;
}
public:
/**
* @param A, B: Two integer arrays.
* @return: Their smallest difference.
*/
int smallestDifference(vector<int> &A, vector<int> &B) {
sort(A.begin(), A.end()); int ret = INT_MAX;
for(auto vb : B)
{
ret = min(ret, _findClosest(A, vb));
}
return ret;
}
};