Welcome

首页 / 软件开发 / 数据结构与算法 / 算法练习:数组的距离

算法练习:数组的距离2015-02-15内容:已知两个元素从小到大排列数组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; }
实验结果是:

From:csdn博客 birdlove1987_