找到最近的相同X和相同Y的点【LC1779】
You are given two integers,
xandy, which represent your current location on a Cartesian grid:(x, y). You are also given an arraypointswhere eachpoints[i] = [ai, bi]represents that a point exists at(ai, bi). 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
(x1, y1)and(x2, y2)isabs(x1 - x2) + abs(y1 - y2).
就是很奇怪 csdn发布文章总是要用手机的热点 校园网就进不来
-
思路:遍历points数组,当point的横坐标与x相等或者纵坐标与y相等时,计算其与给定点的曼哈顿距离,返回距离最小的point的index即可
-
实现
class Solution { public int nearestValidPoint(int x, int y, int[][] points) { int minIndex = -1; int minDis = Integer.MAX_VALUE; for (int i = 0; i < points.length; i++){ if (points[i][0] == x || points[i][1] == y){ int dis = Math.abs(x - points[i][0]) + Math.abs(y - points[i][1]); if (dis < minDis){ minIndex = i; minDis = dis; } } } return minIndex; } }-
复杂度
- 时间复杂度:O(logn)O(log n)O(logn)
- 空间复杂度:O(1)O(1)O(1)
-

本文介绍了一个算法问题:在二维平面上找到与指定位置共享相同X或Y坐标的最近点,并给出了具体的实现方法。
311

被折叠的 条评论
为什么被折叠?



