612. 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]]

代码

/**
 * 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 {
    public static void main(String[] args) {
        int k = 3;
        Point[] result = new Point[k];
        Point origin = new Point(0, 0);
        Point[] points = {
                new Point(4, 6), 
                new Point(4, 7), 
                new Point(4, 4),
                new Point(2, 5), 
                new Point(1, 1) 
        };
        result = kClosest(points, origin, k);
        for (Point p : result) {
            System.out.println("[" + p.x + "," + p.y + "]");
        }
    } 

    public Point[] kClosest(Point[] points, Point origin, int k) {
        Point[] result = new Point[k];
        Point tmpPoint = new Point();
        for (int i = 0; i < points.length; i++) {
            for (int j = i; j < points.length; j++) {
                //比较点和origin点的距离,若前面的点的距离大于后面点的距离,则交换两个点的位置
                if (calcLength(points[i], origin) > calcLength(points[j],
                        origin)) {
                    tmpPoint = points[i];
                    points[i] = points[j];
                    points[j] = tmpPoint;
                }//如果两个点有相同距离,则按照x值来排序
                else if (calcLength(points[i], origin) == calcLength(
                        points[j], origin)) {
                    if (points[i].x > points[j].x) {
                        tmpPoint = points[i];
                        points[i] = points[j];
                        points[j] = tmpPoint;
                    }//若x值相同,按照y值排序。 
                    else if (points[i].x == points[j].x) {
                        if (points[i].y == points[j].y) {
                            tmpPoint = points[i];
                            points[i] = points[j];
                            points[j] = tmpPoint;
                        }
                    }
                }
            }
        }
        //输出符合条件的前k的点
        for (int i = 0; i < k; i++) {
            result[i] = points[i];
        }
        return result;
    }

    //计算两点间距离
    public static double calcLength(Point point, Point origin) {
        double length = Math.sqrt((point.x - origin.x) * (point.x - origin.x)
                + (point.y - origin.y) * (point.y - origin.y));
        return length;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值