程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

973. k points closest to the origin (Python Implementation)

編輯:Python

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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved