面试题 16.06. 最小差

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

https://leetcode.cn/problems/smallest-difference-lcci/description/


示例:

输入:{1, 3, 15, 11, 2}, {23, 127, 235, 19, 8}
输出:3,即数值对(11, 8)

代码


class Solution {
public:
    int smallestDifference(vector<int>& a, vector<int>& b) {
        sort(a.begin(),a.end());
        sort(b.begin(),b.end());
        int p = 0,q = 0;
        long long res = LLONG_MAX;
        while(p < a.size() && q < b.size()){
            res = min(res,llabs(a[p]-b[q]));
            if(a[p] == b[q]){
                break;
            }
            else if(a[p] > b[q]){
                q++;
            }else{
                p++;
            }
        }
        return res;
    }
};
posted @ 2024-05-21 20:25  xiazichengxi  阅读(19)  评论(0)    收藏  举报