mirror of
https://github.com/prdlk/leetcode.git
synced 2026-11-02 13:12:44 +00:00
76 lines
2.3 KiB
Plaintext
76 lines
2.3 KiB
Plaintext
---
|
|
title: '973. K Closest Points to Origin'
|
|
description: 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)
|
|
icon: dot
|
|
topics:
|
|
- { name: "Array", slug: "array" }
|
|
- { name: "Math", slug: "math" }
|
|
- { name: "Divide and Conquer", slug: "divide-and-conquer" }
|
|
- { name: "Geometry", slug: "geometry" }
|
|
- { name: "Sorting", slug: "sorting" }
|
|
- { name: "Heap (Priority Queue)", slug: "heap-priority-queue" }
|
|
- { name: "Quickselect", slug: "quickselect" }
|
|
- { name: "K-D Tree", slug: "k-d-tree" }
|
|
video: "rI2EBUEMfTk"
|
|
issue: "https://github.com/prdlk/leetcode/issues/119"
|
|
sidebar:
|
|
label: 'K Closest Points to Origin'
|
|
badge: 'Medium'
|
|
---
|
|
|
|
### 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 <= 10^4`
|
|
- `-10^4 <= xi, yi <= 10^4`
|
|
|
|
## Approach
|
|
|
|
```mermaid
|
|
flowchart TD
|
|
S(["kClosest(points, k)"]) --> I["minHeap = []"]
|
|
I --> F{"more x, y in points?"}
|
|
F -- yes --> D["dist = x**2 + y**2 — squared distance orders the same as sqrt"]
|
|
D --> A["minHeap.append([dist, x, y])"]
|
|
A --> F
|
|
F -- no --> H["heapq.heapify(minHeap), res = [] — O(n) build, smallest dist on top"]
|
|
H --> W{"k > 0?"}
|
|
W -- yes --> P["dist, x, y = heapq.heappop(minHeap)"]
|
|
P --> R["res.append([x, y]), k -= 1"]
|
|
R --> W
|
|
W -- no --> E(["return res"])
|
|
```
|
|
|
|
## Solution
|
|
|
|
```py
|
|
import heapq
|
|
|
|
|
|
class Solution:
|
|
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
|
|
minHeap = []
|
|
for x, y in points:
|
|
dist = (x**2) + (y**2)
|
|
minHeap.append([dist, x, y])
|
|
|
|
heapq.heapify(minHeap)
|
|
res = []
|
|
|
|
while k > 0:
|
|
dist, x, y = heapq.heappop(minHeap)
|
|
res.append([x, y])
|
|
k -= 1
|
|
|
|
return res
|
|
```
|