Get the two closest points from a list of points

后端 未结 3 1590
爱一瞬间的悲伤
爱一瞬间的悲伤 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:06

    If the points are one dimensional (as in your input is just a list of numbers like [1, 4, 6, 2]), then you can easily do it in O(n log n) time by sorting them and finding the ones with the smallest difference:

    def smallest_difference(points):
        sorted_points = sorted(points)
        return min(abs(prev - cur) for cur, prev in zip(sorted_points, sorted_points[1:]))
    

    If you want to get the closest points instead of the distance between the closest points, use the key= parameter of the min function:

    import operator
    
    def smallest_difference(points):
        sorted_points = sorted(points)
        return min(zip(sorted_points, sorted_points[1:]), key=lambda x: abs(x[1] - x[0]))
    

    If the points are two dimensional (as in your input is a list of 2 element tuples like [(1, 2), (3, 4), (5, 2)]) then the Wikipedia article for this problem https://en.wikipedia.org/wiki/Closest_pair_of_points_problem describes how to extend this to two dimensions.

提交回复
热议问题