Get the two closest points from a list of points

后端 未结 3 1582
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-29 07:14

I am given a list of integers/floats and I need to find the two numbers closest together. How would I do that using only nested for loops?

3条回答
  •  抹茶落季
    2021-01-29 08:03

    Checking each two points is not necessary and it's slow O(n^2).

    I suggest to:
    1) Sort the input.
    2) Compare each two following values and choose smallest.
    Timing will be much better O(n*log n) assuming that you use efficient sorting algorithm.

    Code example:

    input = [0, 65, 10, 100, 1231] #whatever you put here; it might be tuple, list, set, range, etc.
    
    def find_closest(input):
        sorted_input = sorted(input)
        best = (sorted_input[-2], sorted_input[-1], sorted_input[-1] - sorted_input[-2])
        for i, val in enumerate(sorted_input[:-1]):
            d = sorted_input[i+1]-val
            if d < best[2]:
                best = (val, sorted_input[i+1], d) 
    return best
    

    Function returns both values and distance between them.

提交回复
热议问题