K Closest Points(K个最近的点)

http://www.lintcode.com/zh-cn/problem/k-closest-points/?rand=true

/**
 * 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
     */
    public Point[] kClosest(Point[] points, final Point origin, int k) {
        // write your code here
//        对数组进行排序
        Arrays.sort(points, new Comparator() {
            @Override
            public int compare(Point o1, Point o2) {
                if (getDistance(o1, origin) > getDistance(o2, origin)) {
                    return 1;
                } else if (getDistance(o1, origin) < getDistance(o2, origin)) {
                    return -1;
                } else {
                    if (o1.x > o2.x) {
                        return 1;
                    } else if (o1.x < o2.x) {
                        return -1;
                    }
                    return o1.y > o2.y ? 1 : -1;
                }
            }

            private double getDistance(Point a, Point b) {
                return Math.pow(a.x - b.x, 2) + Math.pow(b.y - a.y, 2);
            }
        });
//        复制出想要的k个结果
        Point[] copyOf = Arrays.copyOf(points, k);
        return copyOf;
    }
}

你可能感兴趣的:(K Closest Points(K个最近的点))