题目
- 给定两个整数数组,从两个数组中各取一个元素,要求它们的差值绝对值最小
代码
1. 先排序,后双指针
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr1 = {1, 3, 5, 11};
int[] arr2 = {4, 7, 9};
Arrays.sort(arr1);
Arrays.sort(arr2);
int i = 0, j = 0;
int minDiff = Integer.MAX_VALUE;
int num1 = -1, num2 = -1;
while (i < arr1.length && j < arr2.length) {
int diff = Math.abs(arr1[i] - arr2[j]);
if (diff < minDiff) {
minDiff = diff;
num1 = arr1[i];
num2 = arr2[j];
}
// 如果不需要记录两个数分别是多少,可以直接使用以下语句
// minDiff = Math.min(minDiff, Math.abs(arr1[i] - arr2[j]));
if (arr1[i] < arr2[j]) {
i++;
} else {
j++;
}
}
System.out.println("两个数组中差值绝对值最小的元素是 " + num1 + " 和 " + num2);
System.out.println("它们的差值绝对值是 " + minDiff);
}
}