Leetcode 1779. Find Nearest Point That Has the Same X or Y Coordinate

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Find Nearest Point That Has the Same X or Y Coordinate

2. Solution

解析:Version 1,碰到横纵坐标相等的点计算曼哈顿距离,并与最短距离比较,如果更短,则更新最短距离的点的索引以及最短距离。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:
index = -1
minimum = float('inf')
for i, (x1, y1) in enumerate(points):
if x == x1:
distance = abs(y - y1)
if distance < minimum:
minimum = distance
index = i
elif y == y1:
distance = abs(x - x1)
if distance < minimum:
minimum = distance
index = i
return index

Reference

  1. https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/
如果有收获,可以请我喝杯咖啡!