最小三元组距离
来源:互联网 发布:淘宝店小二的旺旺 编辑:程序博客网 时间: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
- 三元组最小距离
- 最小三元组距离
- 三元组距离最小
- 求解最小三元组距离
- 三元组最小距离[阿里2013校招题目]
- [经典面试题][阿里]三元组最小距离
- 阿里巴巴笔试题求最小三元组距离
- 2014年阿里巴巴笔试题目(28题):最小三元数组距离最优算法
- 最小距离
- 三元组
- 最小编辑距离
- 最小编辑距离
- 最小距离问题
- 凸多边形间最小距离
- 四点求距离最小
- 最小距离之和-中位数
- java最小距离
- 最小距离分类法介绍
- 2012/3/28----堆排序
- 第1周作业-程序练手
- windows8.1 ssd优化
- linux下如何使用有道词典
- Web.XML 配置详解
- 最小三元组距离
- 2012/3/29----快速排序
- sort 1425
- 2012/3/30----冒泡排序
- 2012/3/31----计数排序
- Struts2使用action属性来接收参数
- MongoDB安装成为Windows服务及日常使用遇到问题总结
- openjdk和jdk的区别与联系
- 2012/4/1----基数排序