[LintCode] 最小差 The Smallest Difference

给定两个整数数组(第一个是数组 A,第二个是数组 B),在数组 A 中取 A[i],数组 B 中取 B[j],A[i] 和 B[j]两者的差越小越好(|A[i] - B[j]|)。返回最小差。
样例
给定数组 A = [3,4,6,7], B = [2,3,8,9],返回 0。
挑战
时间复杂度 O(n log n)

Given two array of integers(the first array is array A, the second array is array B), now we are going to find a element in array A which is A[i], and another element in array B which is B[j], so that the difference between A[i] and B[j] (|A[i] - B[j]|) is as small as possible, return their smallest difference.

Example
For example, given array A = [3,6,7,4], B = [2,8,9,3], return 0
Challenge
O(n log n) time

public class Solution {
    /**
     * @param A, B: Two integer arrays.
     * @return: Their smallest difference.
     */
    public int smallestDifference(int[] A, int[] B) {
        int min  = Math.abs(A[0]-B[0]);
        Arrays.sort(B);
        for(int i = 0; i < A.length; i++) {
            int l = 0, r = B.length - 1;
            while(l <= r) {
                int mid = (l + r)/2;
                if(B[mid] == A[i]) {
                    min = 0;
                    break;
                }else if(B[mid] < A[i]) {
                    l = mid + 1;
                }else {
                    r = mid - 1;
                }
            }
            if(l > r) {
                if(l > B.length-1) {
                    min = Math.min(min, A[i]-B[r]);
                } else if(r < 0) {
                    min = Math.min(min, B[l]-A[i]);
                }else{
                    min = Math.min(min, Math.min(A[i]-B[r], B[l]-A[i]));
                }
            }
        }
        return min;
    }
}

你可能感兴趣的:(LintCode,java,Array)