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; }
相关文章推荐
- jQuery限制图片大小的方法
- Angularjs过滤器使用详解
- jQuery中设置form表单中action值的实现方法
- Animate CSS
- JSONModel 的使用总结
- 常用的js工具库
- Javascript模板引擎mustache.js详解
- 改变状态栏样式
- 美化加载失败的图片(Stying broken images)
- (礼拜三log)前端开发:好用的日历插件推荐 plus table使用的注意事项
- mustache.js的使用说明
- Backbonejs之collection
- javascript之JSON引入
- 使用jquery提交form表单并自定义action的实现代码
- javascript之JSON引入
- jQuery.validator自定义验证
- html的meta总结
- jQuery改变form表单的action,并进行提交的实现代码
- jQuery短信验证倒计时功能实现方法详解
- 通过js提示文本框仅能输入数字或者数字+字母