![]() |
VOOZH | about |
Given a 2D array points[][] and an integer k, where each element of points represents a point [xi, yi] on the X-Y plane, find the k points that are closest to the origin (0,0) in any order.
Note: The distance between two points on a plane is the Euclidean distance
Examples:
Input: k = 2, points = [[1, 3], [-2, 2], [5, 8], [0, 1]]
Output: [[-2, 2], [0, 1]]
Explanation: The Euclidean distances from the origin are:
Point (1, 3) = sqrt(10)
Point (-2, 2) = sqrt(8)
Point (5, 8) = sqrt(89)
Point (0, 1) = sqrt(1)
The two closest points to the origin are [-2, 2] and [0, 1].Input: k = 1, points = [[2, 4], [-1, -1], [0, 0]]
Output: [[0, 0]]
Explanation: The Euclidean distances from the origin are:
Point (2, 4) = sqrt(20)
Point (-1, -1) = sqrt(2)
Point (0, 0) = sqrt(0)
The closest point to origin is [0, 0].
Table of Content
The idea is that calculate the squared distance of all the points from the origin and then sort the points based on these distances. Since comparing squared distances gives the same result as comparing actual distances, we don’t need to use square roots. After sorting, we just take the first k points, which will be the closest to the origin.
0, 1 -2, 2
The idea is to use QuickSort’s partitioning. We pick one point as a pivot(usually last) and move all points closer than it to the left and all points farther to the right, placing the pivot in its correct position. Then we check the left side including the pivot: if it has exactly k points, they are the closest. If it has more than k, we search only in the left side. If it has fewer, we take all left points and search for the remaining points in the right side, reducing k by the number of points already taken.
0, 1 -2, 2
The idea is to use a priority queue (max-heap) to keep track of the k closest points to the origin based on their squared distances. After each iteration over the array, we update our queue so that the priority queue always contains the k closest points.
-2, 2 0, 1