subject :
Given an array points , among points[i] = [xi, yi] Express X-Y A point on the plane , And is an integer k , Return from origin (0,0) Current k A little bit .
here , The distance between two points on the plane is Euclid distance ( √(x1 - x2)2 + (y1 - y2)2 ).
You can press In any order Return to the answer . In addition to the order of point coordinates , answer Make sure yes only Of .
Example 1:
Input :points = [[1,3],[-2,2]], k = 1
Output :[[-2,2]]
explain :
(1, 3) The distance from the origin is sqrt(10),
(-2, 2) The distance from the origin is sqrt(8),
because sqrt(8) < sqrt(10),(-2, 2) Closer to the origin .
We just need the closest to the origin K = 1 A little bit , So the answer is [[-2,2]].
Example 2:
Input :points = [[3,3],[5,-1],[-2,4]], k = 2
Output :[[3,3],[-2,4]]
( answer [[-2,4],[3,3]] It will also be accepted .)
Code :
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
temp1, temp2 = [], []
for x in points:
r = x[0]**2 + x[1]**2
if len(temp1)<k:
temp1.append(r)
temp2.append(x)
else:
if r < max(temp1):
site = temp1.index(max(temp1))
temp1[site], temp2[site] = r, x
return temp2