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<Point> comparator = new Comparator<Point>(){
    @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<Point> pq = new PriorityQueue<Point>(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;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值