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 1:
Input: points = [[1,3],[-2,2]], k = 1
Output: [[-2,2]]
Explanation:
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(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:
Input: points = [[3,3],[5,-1],[-2,4]], k = 2
Output: [[3,3],[-2,4]]
Explanation: The answer [[-2,4],[3,3]] would also be accepted.
Constraints:
- 1 <= k <= points.length <= 104
- -104 <= xi, yi <= 104
code by python:
import math
class BinaryMinHeap:
def __init__(self):
self.items = [None]
def __len__(self):
return len(self.items) - 1
def _percolate_up(self):
cur = len(self)
parent = cur // 2
while parent > 0:
if self.items[cur] < self.items[parent]:
self.items[cur], self.items[parent] = self.items[parent], self.items[cur]
cur = parent
parent = cur // 2
def _percolate_down(self, cur):
smallest = cur
left = 2 * cur
right = 2 * cur + 1
if left <= len(self) and self.items[left] < self.items[smallest]:
smallest = left
if right <= len(self) and self.items[right] < self.items[smallest]:
smallest = right
if smallest != cur:
self.items[cur], self.items[smallest] = self.items[smallest], self.items[cur]
self._percolate_down(smallest)
def insert(self, dist):
self.items.append(dist)
self._percolate_up()
def extract(self):
if len(self) < 1:
return None
root = self.items[1]
self.items[1] = self.items[-1]
self.items.pop()
self._percolate_down(1)
return root
def cal_dist(point):
return point[0] * point[0] + point[1] * point[1]
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
heap = BinaryMinHeap()
dists = []
for point in points:
dist = cal_dist(point)
heap.insert(dist)
dists.append(dist)
kth_dist = [heap.extract() for _ in range(k)][-1]
return [points[idx] for idx, dist in enumerate(dists) if dist <= kth_dist]
'LeetCode' 카테고리의 다른 글
704. Binary Search (0) | 2024.07.23 |
---|---|
200. Number of Islands (2) | 2024.07.16 |
234. Palindrome Linked List (0) | 2024.07.15 |
215. Kth Largest Element in an Array (0) | 2024.07.15 |
20. Valid Parentheses (0) | 2024.07.12 |