Input: nums1 =[1,3,15,11,2], nums2 =[23,127,235,19,8]Output: 3Explanation: The smallest difference is between 11(from nums1) and 8(from nums2), i.e.,|11-8|=3.
Input: nums1 =[10,5,40], nums2 =[50,90,80]Output: 10Explanation: The smallest difference is between 40(from nums1) and 50(from nums2), i.e.,|40-50|=10.
Notice that consecutive elements in a sorted array will have the smallest difference when compared to non-consecutive pairs. Therefore, to find the pair with the smallest difference in a single array, sort the array first and then check the difference between each consecutive pair of elements.
For example, after sorting [1, 3, 15, 11, 2] , the pairs (1,2) and (2, 3) have the smallest difference.
To find the smallest difference between two arrays, we can extend this approach as follows:
Sort both arrays using sorting algorithm with O(n log n) complexity, where n is the size of the larger array.
Use two pointers to traverse the starts of the sorted arrays.
Calculate the difference between elements pointed to by these pointers. If this is smaller than the current minimum difference, update the minimum difference and the corresponding pair of elements.
Move the pointer in the array that has the smaller element to the right. Since the arrays are sorted, moving the smaller element pointer can potentially yield a pair with a smaller difference.
publicclassSolution {
// Function to find the pair with the smallest difference between two// elements from two arrayspublicint[]findSmallestDifferencePair(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0, j = 0;
int minDiff = Integer.MAX_VALUE;
int[] pair =newint[2];
while (i < nums1.length&& j < nums2.length) {
int diff = Math.abs(nums1[i]- nums2[j]);
if (diff < minDiff) {
minDiff = diff;
pair[0]= nums1[i];
pair[1]= nums2[j];
}
if (nums1[i]< nums2[j]) {
i++;
} else {
j++;
}
}
return pair;
}
}