数组-最小差-中等

描述
给定两个整数数组(第一个是数组 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)

题目链接

分析

见程序注释

程序

class Solution {
public:
    /**
     * @param A: An integer array
     * @param B: An integer array
     * @return: Their smallest difference.
     */
    /*
    我们先将两个数组排序,此处,A和B都是排好的。用两个指针 i 和 j
    分别指向这两个数组,初始时,都指向第一个元素,在这个例子里面,
    一个指3,一个指2. 差值是1
    接下来,可以这样思考,既然指向的元素一个大,一个小,那么保持大
    的元素不变,小的元素向前增加,那就有可能缩减这个差,计算出新的
    差之后,再和旧的差比较,比旧的差小,则替换旧的差,成为暂时的最
    小值,直到其中有一个遍历完(因为当有一个遍历完时,再遍历另一个
    数组,得到的差只能更大)
    */
    int smallestDifference(vector<int> &A, vector<int> &B) {
        // write your code here
        sort(A.begin(), A.end());
        sort(B.begin(), B.end());
        int A_index = 0; int B_index = 0;
        int result = 0x7fffffff;
        while(A_index < A.size() && B_index < B.size()){
            result = min(result, abs(A[A_index] - B[B_index]));
            if(A[A_index] > B[B_index])
                B_index++;
            else
                A_index++;
        }
        return result;
        
    }
};


猜你喜欢

转载自blog.csdn.net/qq_18124075/article/details/80764817