您的位置:首页 > Web前端

The Smallest Difference

2016-07-10 12:45 204 查看
Given two array of integers(the first array is array
A
, the second array is array
B
), now we are going to find a element in array A which is A[i], and another element in array B which is B[j], so that the difference between A[i] and B[j] (|A[i] - B[j]|) is as small as possible, return their smallest difference.

Example

For example, given array A =
[3,6,7,4]
, B =
[2,8,9,3]
, return
0。


分析:

首先sort, 然后用两个指针分别指向两个array的头部,谁小移动谁。

public class Solution {
/**
* @param A, B: Two integer arrays.
* @return: Their smallest difference.
*/
public int smallestDifference(int[] A, int[] B) {
Arrays.sort(A);
Arrays.sort(B);

int pa = 0;
int pb = 0;

int diff = Integer.MAX_VALUE;

while (pa < A.length && pb < B.length) {
if (A[pa] < B[pb]) {
diff = Math.min(diff, Math.abs(A[pa] - B[pb]));
pa++;
} else if (A[pa] == B[pb]) {
return 0;
} else {
diff = Math.min(diff, Math.abs(A[pa] - B[pb]));
pb++;
}
}
return diff;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: