您的位置:首页 > Web前端

LintCode 387. The Smallest Difference

2016-05-25 10:23 274 查看
Two Pointers, Time complexity O(N), Space O(1)

#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
using namespace std;

/*
Given two array of integer (A and B). Now we are going to find a element in A and another
element in B, so that the difference between A[i] and B[j] |A[i] - B[j]| is as small as
possible, return their smallest difference.
*/

int smallestDifference(vector<int>& A, vector<int>& B) {
sort(A.begin(), A.end());
sort(B.begin(), B.end());
int res = INT_MAX;
int i = 0, j = 0;
while(i < A.size() && j < B.size()) {
int diff = (A[i] - B[j]);
if(diff == 0) return 0;
res = min(res, abs(diff));
if(diff < 0) i ++;
else j++;
}
while(i < A.size()) {
res = min(res, abs(A[i] - B[j - 1]));
i++;
}
while(j < B.size()) {
res = min(res, abs(A[i - 1] - B[j]));
j++;
}
return res;
}

int main(void) {
vector<int> A{3, 6, 7, 4};
vector<int> B{2, 8, 9, 3};
cout << smallestDifference(A, B) << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: