两数组最短距离


# -*- 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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值