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
- LintCode 387. The Smallest Difference
- [LintCode] 最小差 The Smallest Difference
- the-smallest-difference
- #387 The Smallest Difference
- #387 The Smallest Difference
- The Smallest Difference
- 387.The Smallest Difference-最小差(中等题)
- 387.The Smallest Difference-最小差(中等题)
- Smallest Difference
- Smallest Difference
- Smallest Difference
- Smallest Difference
- POJ 2718 Smallest Difference
- Smallest Difference-模拟
- poj 2718 Smallest Difference
- poj2718 Smallest Difference
- Smallest Difference(贪心)
- POJ-2718-Smallest Difference
- Mintec.MineSight.3D.v7.0.3
- git remote
- GC是什么? 为什么要有GC?
- android webview中调用了js的混淆
- 学习Spark(1)
- LintCode 387. The Smallest Difference
- android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open dat
- nginx 403forbidden
- java web定时任务的实现
- JavaWeb 服务启动时,在后台启动加载一个线程
- ProgressDialog高级使用
- lintcode ----最小子数组
- windows下AGK的配置
- acm 3 1015 十进制转换