題目鏈接:https://leetcode.cn/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/
題目描述:
給你兩個整數 x
和 y
,表示你在一個笛卡爾坐標系下的 (x, y)
處。同時,在同一個坐標系下給你一個數組 points
,其中 points[i] = [ai, bi]
表示在 (ai, bi)
處有一個點。當一個點與你所在的位置有相同的 x
坐標或者相同的 y
坐標時,我們稱這個點是 有效的 。
請返回距離你當前位置 曼哈頓距離 最近的 有效 點的下標(下標從 0 開始)。如果有多個最近的有效點,請返回下標 最小 的一個。如果沒有有效點,請返回 -1
。
兩個點 (x1, y1)
和 (x2, y2)
之間的 曼哈頓距離 為 abs(x1 - x2) + abs(y1 - y2)
。
示例 1:
輸入:x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]
輸出:2
解釋:所有點中,[3,1],[2,4] 和 [4,4] 是有效點。有效點中,[2,4] 和 [4,4] 距離你當前位置的曼哈頓距離最小,都為 1 。[2,4] 的下標最小,所以返回 2 。
示例 2:
輸入:x = 3, y = 4, points = [[3,4]]
輸出:0
提示:答案可以與你當前所在位置坐標相同。
示例 3:
輸入:x = 3, y = 4, points = [[2,3]]
輸出:-1
解釋:沒有 有效點。
提示:
1 <= points.length <= 104
points[i].length == 2
1 <= x, y, ai, bi <= 104
解法:模擬
依次遍歷每個點,判斷是否滿足有效,若有效再計算與目標點之間的距離。
代碼:
class Solution {
public int nearestValidPoint(int x, int y, int[][] points) {
int result = -1;
int min = Integer.MAX_VALUE;
for (int i = 0; i < points.length; i++) {
if (x == points[i][0] && Math.abs(y - points[i][1]) < min) {
result = i;
min = Math.abs(y - points[i][1]);
}
if (y == points[i][1] && Math.abs(x - points[i][0]) < min) {
result = i;
min = Math.abs(x - points[i][0]);
}
}
return result;
}
}