Advertisement
dorucriv

Find the closest pair from two sorted arrays

Mar 31st, 2020
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.69 KB | None | 0 0
  1. public class Solution {
  2.     public int[] solve(int[] A, int[] B, int C) {
  3.         int i = 0, j = B.length - 1;
  4.         int minAbs = Integer.MAX_VALUE, minI = -1, minJ = -1;
  5.         while (i < A.length && j >= 0) {
  6.             int sum = A[i] + B[j];
  7.             int abs = Math.abs(sum - C);
  8.             if (abs < minAbs || abs == minAbs && i == minI) {
  9.                 minAbs = abs;
  10.                 minI = i;
  11.                 minJ = j;
  12.             }
  13.             if (sum < C) {
  14.                 i++;
  15.             } else if (sum > C) {
  16.                 j--;
  17.             } else { // sum == C
  18.                 break;
  19.             }
  20.         }
  21.         return new int[] { A[minI], B[minJ] };
  22.     }
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement