给定两个整数数组(第一个是数组 A
,第二个是数组 B
),在数组 A 中取 A[i],数组 B 中取 B[j],A[i] 和 B[j]两者的差越小越好(|A[i] - B[j]|)。返回最小差。
Yes
样例
给定数组 A = [3,4,6,7]
, B = [2,3,8,9]
,返回 0
。
挑战
时间复杂度 O(n log n)
标签
Expand
解题思路:
双指针,分别指向2个数组。
public class Solution {
/**
* @param A, B: Two integer arrays.
* @return: Their smallest difference.
*/
public int smallestDifference(int[] A, int[] B) {
// write your code here
Arrays.sort(A);
Arrays.sort(B);
int alen = A.length;int blen = B.length;
int ap = 0; int bp = 0;
int res = Integer.MAX_VALUE;
while(ap<alen&&bp<blen){
res = Math.min(res, Math.abs(A[ap]-B[bp]));
if(A[ap]<=B[bp]) ap++;
else bp++;
}
return res;
}
}