|
| 1 | +package arrays.mindiffsortedarrays; |
| 2 | + |
| 3 | +/** |
| 4 | + * Given two sorted (ascending) arrays of integers, where the integers do not repeat and the two arrays have no common integers. |
| 5 | + * Let x be any integer in the first array, y any integer in the second. Find min(Abs(x-y)). That is, find the smallest |
| 6 | + * difference between any of the integers in the two arrays. |
| 7 | + * <p/> |
| 8 | + * Created by techpanja |
| 9 | + * Created on 1/20/14 3:00 PM. |
| 10 | + */ |
| 11 | +public class MinimumDifferenceSortedArrays { |
| 12 | + |
| 13 | + private MinimumDifferenceSortedArrays() { |
| 14 | + |
| 15 | + } |
| 16 | + |
| 17 | + /* |
| 18 | + * Dynamic approach. O(N^2). |
| 19 | + * */ |
| 20 | + public static int findMinDifference(int[] inputArrayX, int[] inputArrayY) { |
| 21 | + if (inputArrayX.length == 0 || inputArrayY.length == 0) { |
| 22 | + return -1; |
| 23 | + } |
| 24 | + int minDifference = Math.abs(inputArrayX[0] - inputArrayY[0]); |
| 25 | + for (int x : inputArrayX) { |
| 26 | + for (int y : inputArrayY) { |
| 27 | + if (Math.abs(x - y) < minDifference) { |
| 28 | + minDifference = Math.abs(x - y); |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + return minDifference; |
| 33 | + } |
| 34 | + |
| 35 | + /* |
| 36 | + * Using while loop. O(x + y) solution. |
| 37 | + * */ |
| 38 | + public static int findMinDifferenceUsingWhile(int[] inputArrayX, int[] inputArrayY) { |
| 39 | + if (inputArrayX.length == 0 || inputArrayY.length == 0) { |
| 40 | + return -1; |
| 41 | + } |
| 42 | + int minDifference = Math.abs(inputArrayX[0] - inputArrayY[0]); |
| 43 | + int i = 0, j = 0; |
| 44 | + while (i < inputArrayX.length && j < inputArrayY.length) { |
| 45 | + minDifference = Math.min(minDifference, Math.abs(inputArrayX[i] - inputArrayY[j])); |
| 46 | + if (inputArrayX[i] < inputArrayY[j]) { |
| 47 | + i++; |
| 48 | + } else { |
| 49 | + j++; |
| 50 | + } |
| 51 | + |
| 52 | + } |
| 53 | + return minDifference; |
| 54 | + } |
| 55 | + |
| 56 | + public static void main(String[] args) { |
| 57 | + int[] inputArrayX = new int[]{-1, 4, 6}; |
| 58 | + int[] inputArrayY = new int[]{22, 26, 40}; |
| 59 | + System.out.println(findMinDifference(inputArrayX, inputArrayY)); |
| 60 | + System.out.println(findMinDifferenceUsingWhile(inputArrayX, inputArrayY)); |
| 61 | + |
| 62 | + int[] inputArrayI = new int[]{-1, 4, 46}; |
| 63 | + int[] inputArrayJ = new int[]{22, 26, 40}; |
| 64 | + System.out.println(findMinDifference(inputArrayI, inputArrayJ)); |
| 65 | + System.out.println(findMinDifferenceUsingWhile(inputArrayI, inputArrayJ)); |
| 66 | + |
| 67 | + int[] inputArrayA = new int[]{1, 4, 6}; |
| 68 | + int[] inputArrayB = new int[]{2, 9, 13}; |
| 69 | + System.out.println(findMinDifference(inputArrayA, inputArrayB)); |
| 70 | + System.out.println(findMinDifferenceUsingWhile(inputArrayA, inputArrayB)); |
| 71 | + } |
| 72 | +} |
0 commit comments