Wednesday, January 11, 2017

Find K Nearest Points

Given an array containing n points and an origin point, find k nearest points to the origin point in 2D plane.

/*
Maintain a max-heap storing Points. Need to override the Comparator.

time:O(nlogk), space:O(k)
*/

public class kNearestPoints {
    class Point {
        double x;
        double y;
        public Point(double x, double y) {
            this.x = x;
            this.y = y;
        }
    }
    public Point[] Solution(Point[] array, Point origin, int k) {
        if (array == null || array.length == 0 || k <= 0) {
            return new Point[0];
        }
        PriorityQueue<Point> pq = new PriorityQueue<>(k + 1, 
                                         new Comparator<Point>(){
            public int compare(Point a, Point b) {
                if (getDistance(b, origin) > 
                    getDistance(a, origin)) {
                    return 1;
                } else if (getDistance(b, origin) < 
                           getDistance(a, origin)) {
                    return -1;
                }
                return 0;
            }  
        });
        for (int i = 0; i < array.length; i++) {
            pq.offer(array[i]);
            if (pq.size() > k) {
                pq.poll();
            }
        }
        Point[] ans = new Point[k];
        int index = k - 1;
        while (!pq.isEmpty()) {
            ans[index--] = pq.poll();
        }
    }
    public double getDistance(Point a, Point b) {
        return (a.x - b.x) * (a.x - b.x) + 
               (a.y - b.y) * (a.y - b.y);
    }
}


No comments:

Post a Comment