Binary search.
class Solution { int _findClosest(vector<int> &A, int v) { int s = 0, e = A.size() - 1; int ret = INT_MAX; while(s <= e) { int mid = (s + e) / 2; int vmid = A[mid]; int dist = abs(vmid - v); ret = min(ret, dist); if(vmid == v) return 0; if(vmid < v) { s = mid + 1; } else if(vmid > v) { e = mid - 1; } } 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; } };