[LintCode] 最小差 The Smallest Difference

98 篇文章 0 订阅
17 篇文章 0 订阅

给定两个整数数组(第一个是数组 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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值