【每日算法Day 97】经典面试题:求两个数组最小差
原创
©著作权归作者所有:来自51CTO博客作者godweiyang的原创作品,请联系作者获取转载授权,否则将追究法律责任
题目链接
LeetCode 面试题 16.06. 最小差[1]
题目描述
给定两个整数数组 a
和 b
,计算具有最小差绝对值的一对数值(每个数组中取一个值),并返回该对数值的差。
说明:
-
1 <= a.length, b.length <= 100000
-
-2147483648 <= a[i], b[i] <= 2147483647
- 正确结果在区间
[-2147483648, 2147483647]
内
示例1
输入:
{1, 3, 15, 11, 2}, {23, 127, 235, 19, 8}
输出:
3,即数值对(11, 8)
代码
c++
class Solution {
public:
int smallestDifference(vector<int>& a, vector<int>& b) {
sort(a.begin(), a.end());
sort(b.begin(), b.end());
int n = a.size(), m = b.size();
int i = 0, j = 0;
long res = INT_MAX;
while (i < n && j < m) {
res = min(res, abs(long(a[i])-long(b[j])));
if (a[i] > b[j]) ++j;
else ++i;
}
return res;
}
};
python
class Solution:
def smallestDifference(self, a: List[int], b: List[int]) -> int:
a.sort()
b.sort()
n, m = len(a), len(b)
i, j, res = 0, 0, 2147483647
while i < n and j < m:
res = min(res, abs(a[i]-b[j]))
if a[i] > b[j]: j += 1
else: i += 1
return res
参考资料
[1]
LeetCode 面试题 16.06. 最小差: https://leetcode-cn.com/problems/smallest-difference-lcci/