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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Sort the two arrays, then iterate them in parallel: For each item in
A, search the closest item inBby a linear search. Start the linear search inBwhere you stopped for the previous item ofA. 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
AandB.