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; } };