最小三元组距离

来源:互联网 发布:淘宝店小二的旺旺 编辑:程序博客网 时间:2024/04/28 20:06

题目:

已知三个升序整数数组a[l], b[m]和c[n]。请在三个数组中各找一个元素,使得组成的三元组距离最小。三元组的距离定义是:假设a[i]、b[j]和c[k]是一个三元组,那么距离为:

distance = max(|a[i]-b[j]|, |a[i]-c[k]|, |b[j]-c[k]|)

请设计一个求最小三元组距离的最优算法,并分析时间复杂度。

分析参考:http://blog.csdn.net/ccfeng2008/article/details/12013675

三个数两两之差的最大值是三个数中的最大值减去三个数中的最小值,即可以将距离公式转换为:

distance = max(a[i],b[j],c[k]) - min(a[i],b[j],c[k]) ,因为数组都为升序,所以每次只需要将min(a[i],b[j],c[k]) 所在数组的索引值加1即可。

时间复杂度为O(l+m+n)

#include <iostream>#include "limits.h"using namespace std;//求三个数的最小值 int t_min(int x, int y, int z) {int tmp = x < y ? x : y;return tmp < z ? tmp : z; }//求三个数的最大值 int t_max(int x, int y, int z) {int tmp = x > y ? x : y;return tmp > z ? tmp : z;}//三个数中的最大差 int triple_dist(int x, int y, int z) {return (t_max(x,y,z) - t_min(x,y,z));}//求最小值所在数组,若为1,最小值在a数组中,将其索引加1,其它类似 int min_index(int x, int y, int z) {int tmp = t_min(x,y,z);//若三数相等,则距离最小为0 if(x==y && y == z)return 0; else if(x == tmp)return 1;else if(y == tmp)return 2;elsereturn 3;}int main() {int a[] = {2,8,13,17,23};int b[] = {3,10,17,25,27,32};int c[] = {7,10,14,25,33};int l = 5, m = 6, n = 6;int ap = 0, bp = 0, cp = 0;int dist = INT_MAX;while(ap < l && bp < m && cp < n) {if(triple_dist(a[ap], b[bp], c[cp]) < dist)dist = triple_dist(a[ap], b[bp], c[cp]);if(min_index(a[ap], b[bp], c[cp]) == 0)break;else if(min_index(a[ap], b[bp], c[cp]) == 1)ap++;else if(min_index(a[ap], b[bp], c[cp]) == 2)bp++;elsecp++;} cout << "The distance is: " << dist;return 0;} 


0 0