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

2021-08-13 10:57:40 浏览数 (1)

1. Description

2. Solution

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

  • Version 1
代码语言:javascript复制
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/

0 人点赞