The Smallest Difference

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.

解题思路:1. 最直接的做法是用两个for循环遍历两个数组,其时间复杂度为O(n2), 题目要求用O(nlogn)的时间复杂度来实现,因此可以考虑对数组进行排序。

     2. 排序之后,两个数组都为升序数组。可以发现,内层的for循环不用每次都从0开始。遍历的时间复杂度变为O(n)。 

public class Solution {
    /**
     * @param A, B: Two integer arrays.
     * @return: Their smallest difference.
     */
    public int smallestDifference(int[] A, int[] B) {
        // write your code here
        if (A == null || B == null || A.length == 0 || B.length == 0) {
            return -1;
        }
        Arrays.sort(A);
        Arrays.sort(B);
        int indexA = 0, indexB = 0;
        int min = Integer.MAX_VALUE;
        while (indexA < A.length && indexB < B.length) {
            min = Math.min(min, Math.abs(A[indexA] - B[indexB]));
            if (A[indexA] < B[indexB]) {
                ++indexA;
            } else {
                ++indexB;
            }
        }
        return min;
    }
}

  

posted @ 2017-08-01 10:56  YuriFLAG  阅读(159)  评论(0编辑  收藏  举报