面试题 16.06. 最小差

面试题 16.06. 最小差
给定两个整数数组a和b,计算具有最小差绝对值的一对数值(每个数组中取一个值),并返回该对数值的差

示例:

输入:{1, 3, 15, 11, 2}, {23, 127, 235, 19, 8}
输出:3,即数值对(11, 8)
class Solution {
public:
    int smallestDifference(vector<int>& a, vector<int>& b) {
        long res = LONG_MAX;
        int a_len = a.size(), b_len = b.size();
        int i = 0, j = 0;
        sort(a.begin(), a.end());
        sort(b.begin(), b.end());
        while(i < a_len && j < b_len){
            if(a[i] == b[j]){
                return 0;
            } else {
                //res = min(res, abs((long)a[i]-(long)b[j]));
                res = min(res, abs( (long)a[i] - (long)b[j]) );
                a[i] > b[j] ? ++j : ++i;
            }
        }
        return res;

    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43599304/article/details/121249674