代码思路:横纵坐标的平方和,放到新list中,然后将新list升序排,取前K个即可。
class Solution(object):
def kClosest(self, points, K):
"""
:type points: List[List[int]]
:type K: int
:rtype: List[List[int]]
"""
mydict = {}
for item in points:
temp = pow(item[0], 2) + pow(item[1], 2)
if temp in mydict.keys():
mydict[temp].append(item)
else:
mydict[temp] = [item]
mylist = sorted(mydict.items(), key=lambda x: x[0])
res = []
num = 0
for item in mylist:
res += item[1]
num += len(item[1])
if num >= K:
break
return res[:K]
代码二
class Solution(object):
def kClosest(self, points, K):
"""
:type points: List[List[int]]
:type K: int
:rtype: List[List[int]]
"""
points.sort(key=lambda x: (x[0] ** 2 + x[1] ** 2))
return points[:K]