码迷,mamicode.com
首页 > 其他好文 > 详细

Microsoft - Find the K closest points to the origin in a 2D plane

时间:2018-04-29 01:14:40      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:compare   poi   microsoft   col   while   ret   mic   pre   sem   

Find the K closest points to the origin in a 2D plane, given an array containing N points.

 

用 max heap 做

 

/*
public class Point {
    public int x;
    public int y;
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
*/
 
public List<Point> findKClosest(Point[] p, int k) {
    PriorityQueue<Point> pq = new PriorityQueue<>(10, new Comparator<Point>() {
        @Override
        public int compare(Point a, Point b) {
            return (b.x * b.x + b.y * b.y) - (a.x * a.x + a.y * a.y);
        }
    });
     
    for (int i = 0; i < p.length; i++) {
        if (i < k)
            pq.offer(p[i]);
        else {
            Point temp = pq.peek();
            if ((p[i].x * p[i].x + p[i].y * p[i].y) - (temp.x * temp.x + temp.y * temp.y) < 0) {
                pq.poll();
                pq.offer(p[i]);
            }
        }
    }
     
    List<Point> x = new ArrayList<>();
    while (!pq.isEmpty())
        x.add(pq.poll());
     
    return x;
}

 

Microsoft - Find the K closest points to the origin in a 2D plane

标签:compare   poi   microsoft   col   while   ret   mic   pre   sem   

原文地址:https://www.cnblogs.com/incrediblechangshuo/p/8970020.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!