LintCode: K个最近的点

注意: 计算平方用Math类里面的pow方法计算,但是这个返回的是一个double类型的数字,如果在lintcode上强制转换为int的话,它会提示精度损失,不给通过,所以我就用两个double相减,如果得出的值大于0,就返回1,如果小于0,就返回-1,如果为0,就返回0;

public static Point[] kClosest(Point[] points, Point origin, int k) {

    Comparator comparator = new Comparator(){
    @Override
    public int compare(Point a, Point b){
        double disA = Math.pow(a.x - origin.x, 2) + Math.pow(a.y - origin.y, 2);
        double disB = Math.pow(b.x - origin.x, 2) + Math.pow(b.y - origin.y, 2);
        double com = disB - disA;
        if ( com == 0) {
            com = b.x - a.x;
            if (com == 0) {
                com = b.y - a.y;
            }
        }  
        if (com > 0) {
            return 1;
        }
        else if (com == 0) {
            return 0;
        }
        else {
            return -1;
        }
    }
    };
PriorityQueue pq = new PriorityQueue(k, comparator);        
        for (Point p : points) {
            pq.offer(p);
            if (pq.size() > k) {
                pq.poll();
            }
        }
        Point[] sortPoints = new Point[k];
        for (int i = k - 1; i >= 0; i--) {
            sortPoints[i] = pq.poll();
        }
        return sortPoints;
    }

 

你可能感兴趣的:(算法题)