luoheng
8/31/2019 - 6:09 AM

数组中两个指定元素的最小距离

def MinD(A, x, y):
    Min, xgrid, ygrid = 1000, -1, -1
    d1, d2 = -1, -1
    for ind, i in enumerate(A):
        if i == x:
            xgrid = ind
            if ygrid != -1 and Min > xgrid - ygrid:
                Min = xgrid - ygrid
                d1, d2 = xgrid, ygrid
        if i == y:
            ygrid = ind
            if xgrid != -1 and Min > ygrid - xgrid:
                Min = ygrid - xgrid
                d1, d2 = xgrid, ygrid

    return Min, d1, d2

def main():
    A = [1, 4, 3, 2, 6, 5, 6, 7, 4, 3, 2, 3, 1, 5, 9, 8, 6, 4, 2, 5]
    print(MinD(A, 5, 1))
    print(MinD(A, 2, 7))

if __name__ == "__main__":
    main()