You are given two integers,
x
and y
, which represent your current location on a Cartesian grid: (x, y)
. You are also given an array points
where each points[i] = [a<sub>i</sub>, b<sub>i</sub>]
represents that a point exists at (a<sub>i</sub>, b<sub>i</sub>)
. A point is valid if it shares the same x-coordinate or the same y-coordinate as your location.Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return
-1
.The Manhattan distance between two points
(x<sub>1</sub>, y<sub>1</sub>)
and (x<sub>2</sub>, y<sub>2</sub>)
is abs(x<sub>1</sub> - x<sub>2</sub>) + abs(y<sub>1</sub> - y<sub>2</sub>)
.Example 1:
Input: x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]
Output: 2
Explanation: Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1. [2,4] has the smallest index, so return 2.
Example 2:
Input: x = 3, y = 4, points = [[3,4]]
Output: 0
Explanation: The answer is allowed to be on the same location as your current location.
Example 3:
Input: x = 3, y = 4, points = [[2,3]]
Output: -1
Explanation: There are no valid points.
Constraints:
1 <= points.length <= 10<sup>4</sup>
points[i].length == 2
*
1 <= x, y, a<sub>i</sub>, b<sub>i</sub> <= 10<sup>4</sup>
题目大意:
给定一个坐标和一堆坐标,这个坐标与某个点在同一条y轴或x轴上叫合法点,求它到这些点的最小曼哈顿距离对应的点的下标,若有多个结果,返回最小的数组下标。
解题思路:
Easy题,根据题意求
解题步骤:
N/A
注意事项:
Python代码:
1
2
3
4
5
6
7
8
9
10
11def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:
min_dis = float('inf')
res = -1
for i, (_x, _y) in enumerate(points):
if x == _x or y == _y:
if abs(x - _x) + abs(y - _y) < min_dis:
min_dis = abs(x - _x) + abs(y - _y)
res = i
elif abs(x - _x) + abs(y - _y) == min_dis and i < res:
res = i
return res
算法分析:
时间复杂度为O(n)
,空间复杂度O(1)