LintCode:M-K个最近的点

LintCode链接

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

样例

给出 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 cmpr = new Comparator(){
            public int compare(Node a, Node b){
                if(a.len>b.len)
                    return -1;
                else if(a.lenb.p.x){
                        return -1;
                    }else if(a.p.xb.p.y)
                            return -1;
                        else if(a.p.y maxHeap = new PriorityQueue(k, cmpr);
       int n = points.length;
       for(int i=0; ik){
               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)