码迷,mamicode.com
首页 > 其他好文 > 详细

The Smallest Difference

时间:2016-01-15 07:34:11      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

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) {
        // write your code here
        if(A.length==0 ||A==null ||B.length==0||B==null) return 0;
        int min=Integer.MAX_VALUE;
        Arrays.sort(B);
        for(int i=0;i<A.length;i++)
        {
            int key=A[i];
            int l=0;
            int r=B.length-1;
            while(l<r)
            {
                int mid=(l+r)/2;
                if(key==B[mid]) return 0;
                else if(key>B[mid])
                {
                    l=mid+1;
                }
                else
                {
                    r=mid-1;
                }
                min=Math.min(min,Math.abs(key-B[mid]));
            }
            if(l==r)
            {
                min=Math.min(min,Math.abs(key-B[l]));
            }
        }
        return min;
    }
}

 

The Smallest Difference

标签:

原文地址:http://www.cnblogs.com/kittyamin/p/5132206.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!