K Closest Points解题报告

Description:

Given some points and a point origin in two dimensional space, find k points out of the some points which are nearest to origin.
Return these points sorted by distance, if they are same with distance, sorted by x-axis, otherwise sorted by y-axis.
找出离原点最近的k个点,按照一定顺序排序

Example:

Given points = [[4,6],[4,7],[4,4],[2,5],[1,1]], origin = [0, 0], k = 3
return [[1,1],[2,5],[4,4]]

Link:

http://www.lintcode.com/en/problem/k-closest-points/

解题思路:

用priority queue就可解决。
优先队列的比较方法:
bool function(type a, type b)
如果返回0,则队列中a排在前面,反之则b排在前面。

Tips:

for(Point p: points) { pq.push(p); if(pq.size() > k) pq.pop(); }
这段代码可以节省空间,并且能保证不会漏掉任何一个点。

Time Complexity:

O(N)

完整代码:

int getDistance(Point &a, Point &b) { return (a.x-b.x) * (a.x-b.x) + (a.y - b.y) * (a.y - b.y); } Point originPoint; struct compare { bool operator() (Point &a, Point &b) { int diff = getDistance(a, originPoint) - getDistance(b, originPoint); if(diff == 0) diff = a.x - b.x; if(diff == 0) diff = a.y - b.y; return diff < 0; } }; class Solution { public: vector<Point> kClosest(vector<Point>& points, Point& origin, int k) { originPoint = origin; priority_queue <Point, vector<Point>, compare> pq; for(Point p: points) { pq.push(p); if(pq.size() > k) pq.pop(); } vector <Point> result; while(!pq.empty()) { Point p = pq.top(); result.push_back(p); pq.pop(); } reverse(result.begin(), result.end()); return result; } };

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,351评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,472评论 0 23
  • 我们总是忽略阳光的胎记,正如 忽略春天的第一株草 记忆被当作棉花缝进枕头 装得密不透风 偶尔也会有几朵羽毛漏出来 ...
    临冬雪狼阅读 1,800评论 0 0
  • 看完晨读以后,马上就把我和郭叔叔都代入到内向型人格特质去做了很认真的测评。郭叔叔果然是个不折不扣的内向型直男,而一...
    核心迎春阅读 2,607评论 2 5
  • 刘颖 中国地质大学,初进这所大学,便被它独特的气息所吸引,两旁浓密的大树给这所理工科学校增添了人文气息。而后来的了...
    爱心驿站阅读 1,027评论 0 0