[LeetCode] Find Nearest Point That Has the Same X or Y Coordinate

1779. Find Nearest Point That Has the Same X or Y Coordinate

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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int nearestValidPoint(int x, int y, vector<vector<int>>& p) {
int res = -1, mi = INT_MAX;

for(int i = 0; i < p.size() and mi; i++) {
if(x == p[i][0] or y == p[i][1]) {
int dis = abs(x-p[i][0]) + abs(y-p[i][1]);
if(dis < mi) {
mi = dis;
res = i;
}
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/27/PS/LeetCode/find-nearest-point-that-has-the-same-x-or-y-coordinate/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.