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;
    }
}

  

转载于:https://www.cnblogs.com/FLAGyuri/p/7267329.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值