Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public int[][] kClosest(int[][] points, int K) {
- PriorityQueue<Point> pq = new PriorityQueue<>(K);
- for (int[] point : points) {
- double distance = distance(point);
- Point p = new Point();
- p.distance = distance;
- p.point = point;
- pq.add(p);
- }
- int[][] result = new int[K][2];
- for (int i = 0; i < K; i++) {
- result[i] = pq.poll().point;
- }
- return result;
- }
- private double distance(int[] point) {
- int x = point[0];
- int y = point[1];
- double distance = Math.sqrt(x * x + y * y);
- return distance;
- }
- private static class Point implements Comparable<Point> {
- int[] point;
- double distance;
- @Override
- public int compareTo(Point o) {
- double td = this.distance;
- double od = o.distance;
- return Double.compare(td, od);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement