题目:
给定两个整数数组a和b,计算具有最小差绝对值的一对数值(每个数组中取一个值),并返回该对数值的差
示例:
输入:{1, 3, 15, 11, 2}, {23, 127, 235, 19, 8}
输出:3,即数值对(11, 8)
代码实现:
class Solution {标签:yyds,return,int,res,dif,abs,金典,LeetCode,Math From: https://blog.51cto.com/u_13321676/6084332
public int smallestDifference(int[] a, int[] b) {
int m = a.length;
int n = b.length;
if (m == 1 && n == 1) {
return Math.abs(a[0] - b[0]);
}
Arrays.sort(a);
Arrays.sort(b);
int i = 0;
int j = 0;
long res = Long.MAX_VALUE;
while (i < m && j < n) {
if (a[i] == b[j]) {
return 0;
}
long dif = a[i] - b[j];
res = Math.min(Math.abs(dif), res);
if (dif > 0) {
j++;
} else {
i++;
}
}
return (int) res;
}
}