[LeetCode] 5680. Find the nearest point with the same X or Y coordinate (C++)

1 topic description

  • Give you two integers x and y, which means you are at (x, y) in a Cartesian coordinate system. At the same time, give you an array of points in the same coordinate system, where points[i] = [ai, bi] means that there is a point at (ai, bi). When a point has the same x-coordinate or the same y-coordinate with your location, we call this point valid.
  • Please return the index of the effective point closest to your current location in Manhattan (the index starts from 0). If there are multiple nearest valid points, please return the one with the smallest subscript. If there is no valid point, please return -1.
  • The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1-x2) + abs(y1-y2).

2 Example description

2.1 Example 1

Input: x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]
Output: 2
Explanation: All points Among them, [3,1], [2,4] and [4,4] are valid points. Among the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, both being 1. [2,4] has the smallest subscript, so 2 is returned.

2.2 Example 2

Input: x = 3, y = 4, points = [[3,4]]
Output: 0
Tip: The answer can be the same as your current location.

2.3 Example 3

Input: x = 3, y = 4, points = [[2,3]]
Output: -1
Explanation: There is no valid point.

3 Problem solving tips

1 <= points.length <= 10^4
points[i].length == 2
1 <= x, y, ai, bi <= 10^4

4 Problem-solving ideas

Double Hundred Ideas:
1. Judge the minimum difference of
the ordinate when the abscissa is the same 2. Judge the minimum difference of the abscissa when the ordinate is the same

5 Detailed source code (C++)

class Solution {
    
    
public:
    int nearestValidPoint(int x, int y, vector<vector<int>>& points) {
    
    
        int Min_index = -1 ;
        int Min_distance = INT_MAX ;
        for ( int i = 0 ; i < points.size() ; i ++ )
        {
    
    
            if ( points[i][0] == x && abs( points[i][1] - y) < Min_distance )
            {
    
    
                Min_index = i ;
                Min_distance = abs( points[i][1] - y) ;
            }
            if ( points[i][1] == y && abs( points[i][0] - x) < Min_distance )
            {
    
    
                Min_index = i ;
                Min_distance = abs( points[i][0] - x) ;
            }
        }
        return Min_index ;
    }
};

Guess you like

Origin blog.csdn.net/Gyangxixi/article/details/114477694