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
- Top K nearest points to the origin
- K closest point to the origin
- USING SAS TO FIND THE BEST K FOR K-NEAREST-NEIGHBOR CLASSIFICATION
- K closest points to a given point
- A Detailed Introduction to K-Nearest Neighbor (KNN) Algorithm
- k-Nearest Neighbor algorithm
- K Nearest Neighbor 算法
- k-Nearest Neighbors算法
- k Nearest Neighbors 简介
- K Nearest-Neighbour 总结
- K-Nearest Neighbors algorithm
- K Nearest Neighbor算法
- K Nearest Neighbors - Classification
- K Nearest Neighbor 算法
- K-Nearest Neighbors KNN
- K Nearest Neighbor 算法
- K-Nearest Neighbor Algorithm
- Understanding k-Nearest Neighbour
- HTTP/1.1 413 FULL head
- 第十七周项目2-5-比较两字符串,返回值同strcmp()(指针做形参)
- 汇编例子网址 intel
- sqlite函数大全
- MIPI接口介绍
- Top K nearest points to the origin
- Linux内核中ioremap映射的透彻理解
- 变与不变
- DB2 57011 错误
- java程序员菜鸟进阶(十六)linux基础入门(四)linux下VIM文本编辑器使用
- 番茄红素2
- 如果说这个世界不是真实存在的,只是一段代码,迄今为止你发现了哪些bug?
- UIWebView上Touch/UITapGestureRecognizer事件的最简单的方法
- shell排序