# -*- coding: cp936 -*-
'''
两数组最短距离
已知两个元素从小到大排列的数组x[]与y[],请编写一个程序算出两个数组元素
彼此之间差的绝对值中最小的一个数,此值称做数组的距离。
【说明】
如果x[i]与y[j]是两个元素,那么lx[i]-y[j]l就是这两个元素之间的距离,
所有填些距离 的极小值,称为数组的距离。
比如说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[l],
还有x[4]与y[2]的距离都是1。
注意,如果x[]与y[]各有m与n个元素,那么元素之间的距离就一共有m*n个;
事实上往往用不着这么多个值,应该活用对x[]与y[]已经排列好的特性,不要把所有的距离都算出来。
'''
def ComputTheShorstDistance(listX, listY):
if len(listX)<0 or len(listY)<0:
return -1
shorstDistance=float('inf')
tempDistance=0
indexX=0
indexY=0
flagChage = 1
while( indexX<len(listX) and indexY<len(listY)):
tempDistance=listY[indexY]-listX[indexX]
if tempDistance<0:
indexY+=1
tempDistance=-tempDistance
else:
indexX+=1
if tempDistance<shorstDistance:
shorstDistance=tempDistance
print "两数组最短距离为%d" %(shorstDistance)
ComputTheShorstDistance([1,3,5,7,9], [2,6,8])
xxxxxxxxxxxxxx
思路相似
xxxxxxxxxxxxxxxxxxx
另附c++解答
#define min(x, y) ((x) < (y) ? (x) : (y))
int min_distance(int x[], int y[], int m, int n)
{
int minimum = INT_MAX; /* INT_MAX is from limits.h */
int index_x = 0, index_y = 0;
while (index_x < m && index_y < n)
if (x[index_x] >= y[index_y]) {
minimum = min(minimum, x[index_x]-y[index_y]);
index_y++;
}
else {
minimum = min(minimum, y[index_y]-x[index_x]);
index_x++;
}
return minimum;
}