LintCode 387. The Smallest Difference

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值