-
Notifications
You must be signed in to change notification settings - Fork 257
/
the-smallest-difference.cpp
56 lines (48 loc) · 1.31 KB
/
the-smallest-difference.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Time: O(max(m, n) * log(min(m, n)))
// Space: O(1)
class Solution {
public:
/**
* @param A, B: Two integer arrays.
* @return: Their smallest difference.
*/
int smallestDifference(vector<int> &A, vector<int> &B) {
if (A.size() > B.size()) {
return smallestDifference(B, A);
}
sort(A.begin(), A.end());
int min_diff = numeric_limits<int>::max();
for (const auto& b : B) {
auto it = lower_bound(A.cbegin(), A.cend(), b);
if (it != A.cend()) {
min_diff = min(min_diff, *it - b);
}
if (it != A.cbegin()) {
--it;
min_diff = min(min_diff, b - *it);
}
}
return min_diff;
}
};
// Time: O(nlogn)
// Space: O(1)
class Solution2 {
public:
/**
* @param A, B: Two integer arrays.
* @return: Their smallest difference.
*/
int smallestDifference(vector<int> &A, vector<int> &B) {
sort(A.begin(), A.end());
sort(B.begin(), B.end());
int i = 0;
int j = 0;
int min_diff = numeric_limits<int>::max();
while (i < A.size() && j < B.size()) {
min_diff = min(min_diff, abs(A[i] - B[j]));
A[i] < B[j] ? ++i : ++j;
}
return min_diff;
}
};