#yyds干货盘点# LeetCode程序员面试金典:最小差

时间:2023-02-24 21:01:30

题目:

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

 

示例:

输入:{1, 3, 15, 11, 2}, {23, 127, 235, 19, 8}

输出:3,即数值对(11, 8)

代码实现:

class Solution {
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;
}
}