找到最近的相同X和相同Y的点【LC1779】
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] = [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) is abs(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(1)