Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c063ec9

Browse files
K Closest Points to Origin
1 parent 5e7bc1c commit c063ec9

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

‎973-k-closest-points-to-origin.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/k-closest-points-to-origin/
3+
4+
Given an array of points where points[i] = [xi, yi] represents a point on
5+
the X-Y plane and an integer k, return the k closest points to the origin (0, 0).
6+
The distance between two points on the X-Y plane is the Euclidean distance
7+
(i.e., √(x1 - x2)2 + (y1 - y2)2).
8+
You may return the answer in any order. The answer is guaranteed to be unique
9+
(except for the order that it is in).
10+
11+
Example 1:
12+
Input: points = [[1,3],[-2,2]], k = 1
13+
Output: [[-2,2]]
14+
Explanation:
15+
The distance between (1, 3) and the origin is sqrt(10).
16+
The distance between (-2, 2) and the origin is sqrt(8).
17+
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
18+
We only want the closest k = 1 points from the origin,
19+
so the answer is just [[-2,2]].
20+
21+
Example 2:
22+
23+
Input: points = [[3,3],[5,-1],[-2,4]], k = 2
24+
Output: [[3,3],[-2,4]]
25+
Explanation: The answer [[-2,4],[3,3]] would also be accepted.
26+
27+
Constraints:
28+
1 <= k <= points.length <= 104
29+
-104 < xi, yi < 104
30+
"""
31+
import math
32+
33+
class Solution:
34+
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
35+
distance = []
36+
for x, y in points:
37+
distance.append([math.sqrt((x**2) + (y**2)), x, y])
38+
39+
distance.sort()
40+
41+
res = []
42+
for index in range(k):
43+
_, x, y = distance[index]
44+
res.append([x, y])
45+
return res

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /