Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).
The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2).
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).
Input: points =[[1,3],[-2,2]], k =1Output: [[-2,2]]Explanation:
The distance between(1,3) and the origin issqrt(10).The distance between(-2,2) and the origin issqrt(8).Since sqrt(8)< sqrt(10),(-2,2)is closer to the origin.We only want the closest k =1 points from the origin, so the answer is just [[-2,2]].
Example 2:
1
2
3
Input: points =[[3,3],[5,-1],[-2,4]], k =2Output: [[3,3],[-2,4]]Explanation: The answer [[-2,4],[3,3]] would also be accepted.
Notice the key requirement here: “K is much smaller than N. N is very large”. Definitely the brute-force solution by finding distance of all element and then sorting them in O(nlgn). But its costlier as we don’t need to sort all the n points as we are only concerned for first k points in the sorted list.
An efficient solution could be to use a max-heap of size k for maintaining k minimum distances.
A max heap has its largest element at the root. Whenever we add a point to the heap and its size exceeds K, we remove the root to discard the farthest point and retain the closest ones.
Use a max-heap to keep track of the k closest points.
Insert points into the heap based on their distance to the origin.
If the heap size exceeds k, remove the point with the maximum distance.
At the end, the heap contains the k closest points.
Using Quickselect, we can select the kth minimum distance from the list of distances in O(n) time. Then, we need to go through the array of points and output the first k elements with a distance less than or equal to the kth minimum distance. This is an O(n) time in-place algorithm with constant space.
Distance Calculation: For each point, calculate the squared Euclidean distance to the origin. The squared distance avoids dealing with floating-point precision issues.
Quickselect: Use the Quickselect algorithm to partition the points such that the k closest points are in the correct positions.
Partition: After applying Quickselect, the first k points in the array are the closest points.