1 <= a.length, b.length <= 100000 -2147483648 <= a[i], b[i] <= 2147483647 The result is in the range [-2147483648, 2147483647]
Solutions
megre sorted list O(nlog(n))
class Solution {
public:
int smallestDifference(vector<int>& a, vector<int>& b) {
sort(a.begin(), a.end());
sort(b.begin(), b.end());
int n1 = a.size(), n2 = b.size();
int i = 0, j = 0;
long prev = LONG_MIN / 2, cur, res = LONG_MAX;
bool previsa = true;
while (i < n1 || j < n2) {
bool curisa = true;
if (i < n1 && (j >= n2 || a[i] < b[j]))
cur = a[i++];
else {
cur = b[j++];
curisa = false;
}
if (previsa != curisa)
res = min(res, cur - prev);
prev = cur;
previsa = curisa;
}
return res;
}
};
binary search O(nlog(n))
class Solution {
public:
int smallestDifference(vector<int>& a, vector<int>& b) {
sort(a.begin(), a.end());
long res = LONG_MAX;
for (long n : b) {
auto it = lower_bound(a.begin(), a.end(), n);
long diff1 = it != a.begin() ? n - *prev(it) : LONG_MAX;
long diff2 = it != a.end() ? *it - n : LONG_MAX;
res = min(res, min(diff1, diff2));
if (res == 0) break;
}
return res;
}
};