Suppose I have two random arrays of ints, say:
int A[] = {484, 834, 591, 23, 174, 248, 147, 765};
int B[] = {659, 805, 12, 180, 771, 386, 354, 568, 710, 312, 6, 848};
I wish to find all close pairs respectively from the two arrays, where the difference between two ints are not greater than some fixed k like 50:
(from A, from B)
(834, 805)
(834, 848)
(591, 568)
(23, 12)
(23, 6)
(174, 180)
(147, 180)
(765, 805)
(765, 771)
The trivial way to do that is using a nested for loop:
for (int a : A) {
for (int b : B) {
if (abs(a - b) < k)
// find (a, b)
}
}
but this requires O(n^2) time complexity and seems not efficient. Is there a better way to do that, regardless of space cost?