Find K nearest Points to Point P in 2-dimensional plane

后端 未结 9 1715
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-31 04:27

Source: AMAZON INTERVIEW QUESTION

Given a point P and other N points in two dimensional space, find K points

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-31 04:48

    // point_type pt, length_sq(p) { return pt[0] * pt[0] + pt[1] * pt[1]}
    // std::vector points to search.
    // The algorithm should recursion depth to 
    //       O(k * log(points.size())), and
    // running time to O(points.size()).
    
    std::nth_element(
                   points.begin(),
                   points.begin() + k,
                   points.end(),
                   [&pt](point_type const & a)
                   {
                        return length_squared(a - pt);
                   });
    
    // points[0], ... , points[k - 1] are the closest points to pt
    

提交回复
热议问题