阅读背景:

find k closest point to origin point in 2d plane

来源:互联网 
public List<Point> findKClosest(Point[] p, int k) {
        List<Point> res = new LinkedList<>();
        PriorityQueue<Point> queue = new PriorityQueue<>(11, 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 (Point point: p) {
            if (queue.size() < k) {
                queue.offer(point);
            } else {
                Point a = queue.poll();
                if (point.x * point.x + point.y * point.y - a.x * a.x - a.y * a.y < 0) {
                    queue.poll();
                    queue.offer(point);
                }
            }
        }
        while (!queue.isEmpty()) {
            res.add(queue.poll());
        }
        return res;
    }
    
    class Point {
        int x;
        int y;
        public Point (int x, int y) {
            this.x = x;
            this.y = y;
        }
    }public List<Point> findKClosest(Point[] p, int 



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: