刷题-力扣-面试题 16.06. 最小差

题目链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/smallest-difference-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目描述

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

示例:

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

提示:

  • 1 <= a.length, b.length <= 100000
  • -2147483648 <= a[i], b[i] <= 2147483647
  • 正确结果在区间 [0, 2147483647] 内

题目分析

  1. 根据题目描述,从两个数组中各选择一个数,求存在的差的最小值
  2. 对两个数组按非递增排序,遍历两个数组
  3. 让选取的数组中的较大的数的索引增加,依次执行,直到数组末尾

代码

class Solution {
public:
    int smallestDifference(vector<int>& a, vector<int>& b) {
        int i = 0;
        int j = 0;
        std::sort(a.begin(), a.end(), this->compare);
        std::sort(b.begin(), b.end(), this->compare);
        long res = std::abs(a[0] - b[0]);
        while (i < a.size() && j < b.size()) {
            if (a[i] == b[j]) { return 0; }
            res = std::min(res, (long)std::abs(a[i] - b[j]));
            if (a[i] > b[j]) { ++i; }
            else { ++j; }
        }
        return res;
    }

private:
    static inline bool compare(int a, int b) {
        return a > b;
    }
};
posted @ 2022-05-02 23:26  韩亚光  阅读(20)  评论(0编辑  收藏  举报