Top K nearest points to the origin

来源:互联网 发布:g502 知乎 编辑:程序博客网 时间:2024/06/08 04:25

There are n points in the xy-coordinate system. Find the top K nearest points to the origin.

{(1,2), (-1,2), (3.-3),...}

The idea for this problem is to use the max_heap(yes, the max heap, NOT the min heap) with size K, and define the compare function.

// top K nearest points to the origin// a problem from mitbbs.comstruct Point {    double x;double y;Point(double xx, double yy): x(xx), y(yy){};};double distance(const Point &p) {    return p.x*p.x + p.y*p.y;}struct max_heap_compare {bool operator()(const Point &a, const Point &b) const {return distance(a) < distance(b);}};class Solution {public:std::vector<Point> topKNearest(std::vector<Point> &pts, int k) {    std::vector<Point> res;if (pts.empty()) return res;std::priority_queue<Point, std::vector<Point>, max_heap_compare> max_heap;auto p = pts.begin();while(int(max_heap.size()) < k && p!= pts.end()) {Point a_pt(p->x, p->y);max_heap.push(a_pt);++p;}while(p!=pts.end()) {auto& top_pt = max_heap.top();if(distance(top_pt) > distance(*p)){Point ap(p->x, p->y);max_heap.pop();max_heap.push(ap);}++p;}while(!max_heap.empty()) {Point p = max_heap.top();max_heap.pop();res.push_back(p);}return res;}};


0 0
原创粉丝点击