题目链接
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++
classSolution { public: intsmallestDifference(vector<int>&a, vector<int>&b) { sort(a.begin(), a.end()); sort(b.begin(), b.end()); intn=a.size(), m=b.size(); inti=0, j=0; longres=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; } returnres; } };
python
classSolution: defsmallestDifference(self, a: List[int], b: List[int]) ->int: a.sort() b.sort() n, m=len(a), len(b) i, j, res=0, 0, 2147483647whilei<nandj<m: res=min(res, abs(a[i]-b[j])) ifa[i] >b[j]: j+=1else: i+=1returnres
参考资料
[1]
LeetCode 面试题 16.06. 最小差: https://leetcode-cn.com/problems/smallest-difference-lcci/
作者简介:godweiyang,知乎同名,华东师范大学计算机系硕士在读,方向自然语言处理与深度学习。喜欢与人分享技术与知识,期待与你的进一步交流~

