最小差

来源:互联网 发布:网络端口线连接 编辑:程序博客网 时间:2024/04/28 18:43

给定两个整数数组(第一个是数组 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, B: Two integer arrays.     * @return: Their smallest difference.     */    int smallestDifference(vector<int> &A, vector<int> &B) {        // write your code here        int m = A.size();        int n = B.size();                sort(A.begin(), A.end());        sort(B.begin(), B.end());                int result = INT_MAX;        int i = 0;        int j = 0;        while (i < m && j < n)        {            int temp = abs(A[i] - B[j]);            if (temp < result)            {                result = temp;                if (result == 0)                {                    break;                }            }            if (A[i] < B[j])            {                i++;            }            else            {                j++;            }        }                return result;    }};



0 0