K closest point to the origin

Give n points on 2-D plane, find the K closest points to origin


13     public List KClosest(List input, int k) {
14         List res = new LinkedList();
15         PriorityQueue pq = new PriorityQueue(10, new Comparator() {
16             public int compare(Point a, Point b) {
17                 return (b.x * b.x + b.y * b.y) - (a.x * a.x + a.y * a.y);
18             }            
19         });
20         
21         for (Point each : input) {
22             pq.offer(each);
23             if (pq.size() > k) pq.poll();
24         }
25         while (!pq.isEmpty()) {
26             res.add(0, pq.poll());
27         }
28         return res;
29     }


你可能感兴趣的:(facebook)