1779. 找到最近的有相同 X 或 Y 坐标的点 - 力扣(LeetCode)
可以用以下步骤来解决这个问题:
-
遍历
points
数组; -
检查每个点是否和当前位置
(x, y)
有相同的 x 或 y 坐标; -
如果是有效点,计算它到当前位置的曼哈顿距离;
-
找出所有有效点中距离最小的,如果有多个相同距离的,返回下标最小的。
下面是对应的 Python 实现:
def nearestValidPoint(x, y, points):
min_distance = float('inf')
result_index = -1
for i, (px, py) in enumerate(points):
if px == x or py == y:
distance = abs(px - x) + abs(py - y)
if distance < min_distance:
min_distance = distance
result_index = i
return result_index
示例:
x = 3
y = 4
points = [[1, 2], [3, 1], [2, 4], [2, 3], [4, 4]]
# 调用函数
print(nearestValidPoint(x, y, points)) # 输出 2
这个函数会返回距离最近的有效点的下标。如果没有找到有效点,返回 -1。
需要我用其他语言实现或者加点注释说明吗?