您的位置:首页 > 编程语言 > C语言/C++

每日一小练——数组的距离

2014-05-13 13:41 197 查看
上得厅堂,下得厨房,写得代码,翻得围墙,欢迎来到睿不可挡的每日一小练!

题目:数组的距离

内容:已知两个元素从小到大排列数组x[]和y[],请编写一个程序算出两个数组元素彼此之间差的绝度值中最小的一个

数,此值称作数组的距离。

例如:x[]有1,3,5,7,9   y[]有2,6,8  那么最短距离就是1,因为x[0]和y[0]、x[1]和y[0]、x[2]和y[1]、x[3]和y[1]还有x[4]和

y[2]的距离都是1.

我的解法:上来没多想,打开vs2013就敲了起来,问题果然很简单,分分钟就超神。。奥,不对就解决了!然后发现这个题目有点像某oj上面的题目,不过现在看来还是挺简单滴。。嘿嘿。。我又进步了O(∩_∩)O~。

#include <iostream>
#include <math.h>
#define min(x,y) (x < y ? x : y)
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
int sLength(int x[], int y[], int x_Length, int y_Length);
int x[5] = { 1, 14, 31, 50, 70 };
int y[5] = { 7, 23, 40, 60, 75 };
int sL = sLength(x, y, 5, 5);
cout << "两个数组的最短距离为: " <<  sL  << endl;
getchar();
return 0;
}

int sLength(int x[], int y[], int x_Length, int y_Length)
{
int shortLength = TMP_MAX;
int x_Index = 0;
int y_Index = 0;
while (x_Index < x_Length && y_Index < y_Length)
{
if (x[x_Index] >= y[y_Index])
{
shortLength = min(shortLength, (x[x_Index] - y[y_Index]));
y_Index++;
}
else
{
shortLength = min(shortLength, (y[y_Index] - x[x_Index]));
x_Index++;
}
}
return shortLength;
}


实验结果是:



欢迎大家加入每日一小练,嘿嘿!

每天练一练,日久见功夫,加油!

            -End-

参考文献:《c语言名题精选百则》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息