Created
April 13, 2023 22:38
-
-
Save optimistiks/a5ef012226ac4e9a3a25bd769383e883 to your computer and use it in GitHub Desktop.
Given a list of points on a plane, where the plane is a 2-D array with (x, y) coordinates, find the k closest points to the origin 0,0.
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
| export function kClosest(points, k) { | |
| const heap = new MaxHeap(); | |
| // put initial k points into max heap with their distances | |
| // now we have largest distance seen so far at the top | |
| for (let i = 0; i < k; ++i) { | |
| const distance = getDistance(points[i]); | |
| heap.offer([distance, points[i]]); | |
| } | |
| // iterate the rest of points | |
| for (let i = k; i < points.length; ++i) { | |
| const distance = getDistance(points[i]); | |
| // if distance is smaller than the largest seen so far (top of the heap) | |
| // then largest seen so far is removed from the heap | |
| // and distance is added | |
| if (distance < heap.peek()[0]) { | |
| heap.poll(); | |
| heap.offer([distance, points[i]]); | |
| } | |
| } | |
| // after iterating, we have k closest points in the heap | |
| const result = []; | |
| while (heap.size() > 0) { | |
| const [_, point] = heap.poll(); | |
| result.push(point); | |
| } | |
| return result; | |
| } | |
| function getDistance(point) { | |
| return Math.sqrt(point.x * point.x, point.y * point.y); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
