lintcode-medium-The Smallest Difference

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-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

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

 

以上是关于lintcode-medium-The Smallest Difference的主要内容,如果未能解决你的问题,请参考以下文章

VxWorks Small-Footprint Configuration

<small> 标签使段落的高度变大

small db

Android Small插件化框架源码分析

PHP源码分析-small内存规格的计算

iOS开发常用第三方库