1562. 餐厅的数量
1562. 餐厅的数量
中文English
给出一个List
,里面的数据代表每一个餐厅的坐标[x, y]
。顾客的坐标处于原点[0, 0]
。找出 n
家离顾客位置最近的餐厅,其中 m
为这 n
家餐厅到顾客的最远距离 ,如果列表中存在超过 n
家餐厅到顾客的距离不大于 m
,则按列表内元素顺序返回先出现的 n
家餐厅。
样例
Example 1
Input: n = 2 , List = [[0,0],[1,1],[2,2]]
Output : [[0,0],[1,1]]
Explanation: The closest 2 restaurants are [0,0] and [1,1]. And only these two restaurants are in sqrt(2) meters.
Example 2
Input: n = 3,List = [[0,1],[1,2],[2,1],[1,0]]
Output:[[0,1],[1,2],[2,1]]
Explanation: The closest 3 restaurants are [0,1],[1,2] and [2,1]. And only these three restaurants are in sqrt(5) meters.
注意事项
1.坐标的范围[-1000, 1000]
2.n > 0
3.不存在相同的坐标
排序
class Solution: """ @param restaurant: @param n: @return: nothing """ def nearestRestaurant(self, restaurant, n): # Write your code here if len(restaurant) < n: return [] distances = [] for array in restaurant: dis = array[0]**2 + array[1]**2 distances.append(dis) distances.sort() n_dis = distances[n - 1] results = [] count = 0 for array in restaurant: dis = array[0]**2 + array[1]**2 if dis <= n_dis: results.append(array) count += 1 if count == n: break return results