美文网首页Leetcode
Leetcode 1779. Find Nearest Poin

Leetcode 1779. Find Nearest Poin

作者: SnailTyan | 来源:发表于2021-09-22 08:52 被阅读0次

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

    1. Description

    Find Nearest Point That Has the Same X or Y Coordinate

    2. Solution

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

    • Version 1
    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/

    相关文章

      网友评论

        本文标题:Leetcode 1779. Find Nearest Poin

        本文链接:https://www.haomeiwen.com/subject/xvecbltx.html