How to find two most distant points?

后端 未结 9 2015
旧巷少年郎
旧巷少年郎 2020-11-29 19:05

This is a question that I was asked on a job interview some time ago. And I still can\'t figure out sensible answer.

Question is:

you are given set of points

9条回答
  •  盖世英雄少女心
    2020-11-29 19:54

    Given a set of points {(x1,y1), (x2,y2) ... (xn,yn)} find 2 most distant points.

    My approach:

    1). You need a reference point (xa,ya), and it will be:
    xa = ( x1 + x2 +...+ xn )/n
    ya = ( y1 + y2 +...+ yn )/n

    2). Calculate all distance from point (xa,ya) to (x1,y1), (x2,y2),...(xn,yn)
    The first "most distant point" (xb,yb) is the one with the maximum distance.

    3). Calculate all distance from point (xb,yb) to (x1,y1), (x2,y2),...(xn,yn)
    The other "most distant point" (xc,yc) is the one with the maximum distance.

    So you got your most distant points (xb,yb) (xc,yc) in O(n)

    For example, for points: (0,0), (1,1), (-8, 5)

    1). Reference point (xa,ya) = (-2.333, 2)

    2). Calculate distances:
    from (-2.333, 2) to (0,0) : 3.073
    from (-2.333, 2) to (1,1) : 3.480
    from (-2.333, 2) to (-8, 5) : 6.411
    So the first most distant point is (-8, 5)

    3). Calculate distances:
    from (-8, 5) to (0,0) : 9.434
    from (-8, 5) to (1,1) : 9.849
    from (-8, 5) to (-8, 5) : 0
    So the other most distant point is (1, 1)

提交回复
热议问题