您的位置:首页 > 其它

LintCode:M-K个最近的点

2017-08-30 14:01 218 查看
LintCode链接

给定一些 
points
 和一个 
origin
,从 
points
 中找到 
k
 个离 
origin
 最近的点。按照距离由小到大返回。如果两个点有相同距离,则按照x值来排序;若x值也相同,就再按照y值排序。

您在真实的面试中是否遇到过这个题? 

Yes

样例

给出 points = 
[[4,6],[4,7],[4,4],[2,5],[1,1]]
,
origin = 
[0, 0]
, k = 
3


返回 
[[1,1],[2,5],[4,4]]


维护一个大小为 k 的堆,最后倒序输出

/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
public class Solution {
/**
* @param points a list of points
* @param origin a point
* @param k an integer
* @return the k closest points
*/
class Node{
Point p;
long len;
public Node(Point a, long b){
p=a;
len=b;
}
}
public Point[] kClosest(Point[] points, Point origin, int k) {
Comparator<Node> cmpr = new Comparator<Node>(){
public int compare(Node a, Node b){
if(a.len>b.len)
return -1;
else if(a.len<b.len)
return 1;
else{
if(a.p.x>b.p.x){
return -1;
}else if(a.p.x<b.p.x){
return 1;
}else{
if(a.p.y>b.p.y)
return -1;
else if(a.p.y<b.p.y)
return 1;
else
return 0;
}
}
}
};
Queue<Node> maxHeap = new PriorityQueue<Node>(k, cmpr);
int n = points.length;
for(int i=0; i<n; i++){
Node newNode = new Node(points[i], getLenMul(points[i], origin));
maxHeap.add(newNode);
if(maxHeap.size()>k){
maxHeap.poll();
}
}

Point[] res = new Point[k];
for(int i=k-1; i>=0; i--){
res[i] = maxHeap.poll().p;
}

return res;
}

long getLenMul(Point a, Point b){
return (long) (Math.pow((a.x-b.x),2)+Math.pow((a.y-b.y),2));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LintCode Medium 堆栈