LeetCode 973. K Closest Points to Origin

Post by ailswan Aug. 18, 2024

973. K Closest Points to Origin

Problem Statement

link: LeetCode.cn LeetCode 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).

Example:

Input: points = [[1,3],[-2,2]], k = 1 Output: [[-2,2]]

Input: tree = [7], target = 7 Output: 7

Input: points = [[3,3],[5,-1],[-2,4]], k = 2 Output: [[3,3],[-2,4]]

Constraints: 1 <= k <= points.length <= 104 -104 <= xi, yi <= 104

Solution Approach

The solution uses a max-heap to efficiently keep track of the k closest points by comparing the squared Euclidean distance of each point to the origin.

Algorithm

  1. Calculate Squared Distances: For each point, calculate the squared Euclidean distance to avoid the computational cost of square roots.
  2. Maintain a Max-Heap: Use a max-heap to store the k closest points by pushing the negative squared distance into the heap. If the heap size exceeds k, remove the farthest point.
  3. Return the Result: After processing all points, extract the points from the heap, which now contains the k closest points to the origin.

Implement

    class Solution:
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        # distance2 
        # dists = [] 
        # if len(dists) >= k: heapq.heappushpop(-dists, distance2)
        # else: heapq.heappush(-dists, distance2)
        dists = []
        for x, y in points:
            temp = x ** 2 + y ** 2
            if len(dists) >= k:
                heapq.heappushpop(dists, (-temp, x, y))
            else:
                heapq.heappush(dists,  (-temp, x, y))
        
        return [[point[1], point[2]] for point in dists]