387-最小差
给定两个整数数组(第一个是数组 A,第二个是数组 B),在数组 A 中取 A[i],数组 B 中取 B[j],A[i] 和 B[j]两者的差越小越好(|A[i] - B[j]|)。返回最小差。
样例
给定数组 A = [3,4,6,7], B = [2,3,8,9],返回 0。
挑战
时间复杂度 O(n log n)
标签
两根指针 数组 LintCode 版权所有 排序
思路
一次遍历 + 二分查找,首先遍历数组 A,之后以 A[i] 为目标,对数组 B 进行二分查找,找出 B 中与 A[i] 的最小差
code
class Solution {
public:
/**
* @param A, B: Two integer arrays.
* @return: Their smallest difference.
*/
int smallestDifference(vector<int> &A, vector<int> &B) {
// write your code here
int sizeA = A.size(), sizeB = B.size();
if (sizeA <= 0 || sizeB <= 0) {
return 0;
}
int result = INT_MAX;
sort(B.begin(), B.end());
for (int i = 0; i < sizeA; i++) {
int low = 0, high = sizeB - 1, target = A[i], mid = 0;
while (low <= high) {
mid = low + (high - low) / 2;
if (B[mid] == target) {
return 0;
}
else if (B[mid] < target) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
result = min(result, abs(A[i] - B[mid]));
if(mid > 0) {
result = min(result, abs(A[i] - B[mid - 1]));
}
if (mid < sizeB - 1) {
result = min(result, abs(A[i] - B[mid + 1]));
}
}
return result;
}
};