Created
December 8, 2019 19:03
-
-
Save Transfusion/7b78ca355032b46fc6a6ca0aa32010b1 to your computer and use it in GitHub Desktop.
LC 973. K Closest Points to Origin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| private double euclidDist(int[] p1, int[] p2) { | |
| return Math.sqrt( Math.pow(p1[0] - p2[0], 2) + Math.pow(p1[1] - p2[1], 2) ); | |
| }; | |
| public int[][] kClosest(int[][] points, int K) { | |
| int[] origin = new int[]{0,0}; | |
| PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() { | |
| public int compare(int[] p1, int[] p2) { | |
| double dist1 = euclidDist(p1, origin); | |
| double dist2 = euclidDist(p2, origin); | |
| if (dist1 > dist2) { | |
| return 1; | |
| } else if (dist2 > dist1) { | |
| return -1; | |
| } else { | |
| return 0; | |
| } | |
| } | |
| }); | |
| for (int[] point : points) { | |
| pq.add(point); | |
| } | |
| int[][] closest = new int[K][2]; | |
| for (int i = 0; i < K; i++) { | |
| int[] point = pq.poll(); | |
| closest[i] = point; | |
| } | |
| return closest; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment