lintcode刷题——最小差
来源:互联网 发布:怎样查找网络打印机 编辑:程序博客网 时间:2024/06/06 08:50
原题如下:
最小差
给定两个整数数组(第一个是数组 A
,第二个是数组 B
),在数组 A 中取 A[i],数组 B 中取 B[j],A[i] 和 B[j]两者的差越小越好(|A[i] - B[j]|)。返回最小差。
给定数组 A = [3,4,6,7]
, B = [2,3,8,9]
,返回 0
。
1、首先能想到的方法就是最笨的办法,暴力的双重循环,遍历a和b里面的每一个数据进行对比,显然这种方法复杂度太高,稍加思考,对方法改进;
2、对a和b数组里面的数字可以先进行排序,然后用一层循环,对a和b当前的数据进行比较,如果有相等的,最小差必然为0,如果没有,则取最小的。
具体的C++代码如下:
class Solution {
public:
/**
* @param A, B: Two integer arrays.
* @return: Their smallest difference.
*/
int smallestDifference(vector<int> &A, vector<int> &B) {
// write your code here
sort(A.begin(),A.end());
sort(B.begin(),B.end());
int l1=A.size();
int l2=B.size();
if(l1==0)
{
return A[0];
}
else if(l2==0)
{
return B[0];
}
else if(l1==0&&l2==0)
{
return 0;
}
else
{
int sub=INT_MAX;
int i=0,j=0;
while(i<l1&&j<l2)
{
if(A[i]<B[j])
{
if(abs(A[i]-B[j])<sub)
{
sub=abs(A[i]-B[j]);
}
i++;
}
else if(A[i]>B[j])
{
if(abs(A[i]-B[j])<sub)
{
sub=abs(A[i]-B[j]);
}
j++;
}
else
{
sub=0;
break;
}
}
return sub;
}
}
};
- lintcode刷题——最小差
- LintCode-最小差
- LintCode:最小差
- LintCode:最小差
- lintcode ---最小差
- Lintcode 最小差
- 最小差-LintCode
- [LintCode] 最小差 The Smallest Difference
- 最小子数组—LintCode
- LINTCODE————最小划分
- 算法期中——最小差
- lintcode刷题——和大于S的最小子数组
- lintcode——二叉树的最小深度
- 最小差
- 最小差
- 最小差
- 最小差
- LintCode-最大子数组差
- 阿里云WINDOWS SERVER2012 不能正常发送邮件
- nyoj 36 最长公共子序列
- 爬虫
- Oracle select读的多种形式
- RabbitMq 安装
- lintcode刷题——最小差
- python 6种数据类型几及用法
- HttpClient不同版本超时时间的设置
- 文件查找01
- 基于TLD的人脸检测跟踪系统
- EXPDP命令行选项
- HDU2036 多边形面积模板
- 贝叶斯分类器
- FreeMarker入门二