Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

minimum absolute difference between two numbers in an array [closed]

Given two arrays, A and B, i want to find a number from A and a number from B, such that the absolute difference between the two numbers is the smallest.

Eg

A = 1 2 9
B=  4 5  6

Ans : 2,4 as Math.abs(2-4) =2

like image 598
TimeToCodeTheRoad Avatar asked Mar 13 '11 15:03

TimeToCodeTheRoad


1 Answers

Sort the two arrays, then iterate them in parallel: For each item in A, search the closest item in B by a linear search. Start the linear search in B where you stopped for the previous item of A. Always remember the minimal distance found so far.

The time complexity is O(m log m + n log n) for sorting and O(m + n) for the final search, where m and n are the respective lengths of A and B.

like image 138
Sven Marnach Avatar answered Sep 25 '22 17:09

Sven Marnach