LintCode 387. The Smallest Difference

来源:互联网 发布:灯光秀编程 编辑:程序博客网 时间:2024/05/21 01:56

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;}


0 0
原创粉丝点击