遍历就完了,一边遍历一边找有效坐标再算下曼哈顿距离。
class Solution {
public:
int nearestValidPoint(int x, int y, vector<vector<int>>& points) {
int res = 0;
int min_sum = INT_MAX, index = 0, cnt = 0;
for (int i = 0; i < points.size(); i ++ ) //遍历每个坐标
{
if (points[i][0] == x || points[i][1] == y) //找到有效坐标
{
cnt ++ ; //cnt表示有效坐标个数
if (abs(points[i][0] - x) + abs(points[i][1] - y) < min_sum)
{
min_sum = abs(points[i][0] - x) + abs(points[i][1] - y); //更新最小曼哈顿距离
index = i; //因为是下标按顺序遍历,故不需要判断小标大小,小的肯定先遍历到
}
}
}
if (!cnt) return -1; //不存在有效坐标,返回0
return index;
}
};