Skip to content

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

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int nearestValidPoint(int x, int y, vector<vector<int>>& points) {
    int ans = -1;
    int minDist = INT_MAX;

    for (int i = 0; i < points.size(); ++i) {
      const int dx = x - points[i][0];
      const int dy = y - points[i][1];
      if (dx == 0 || dy == 0) {
        const int dist = abs(dx + dy);
        if (dist < minDist) {
          minDist = dist;
          ans = i;
        }
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int nearestValidPoint(int x, int y, int[][] points) {
    int ans = -1;
    int minDist = Integer.MAX_VALUE;

    for (int i = 0; i < points.length; ++i) {
      final int dx = x - points[i][0];
      final int dy = y - points[i][1];
      if (dx == 0 || dy == 0) {
        final int dist = Math.abs(dx + dy);
        if (dist < minDist) {
          minDist = dist;
          ans = i;
        }
      }
    }

    return ans;
  }
}