[C++] Linear Solution Explained, 100% Time, 100% Space
Pleasant warm up - easy to understand and to execute.\n\nTo solve this problem, we will need 2 support variables first:\n res is where we will store the positio
Pleasant warm up - easy to understand and to execute.\n\nTo solve this problem, we will need 2 support variables first:\n* `res` is where we will store the position of the first best fit we find, initially set to `-1` (which will then be returned when no match has been found);\n* `bestDist` will store the current closest distance across all the matches we found - initially set to `INT_MAX`.\n\nWe will then loop through all the elements in `points` and for each one we will:\n* assign the 2 values inside `points` as `cx` and `cy`;\n* check if `x == cx || y == cy` as per requirements and, in case:\n\t* compute `currDist` as the Manhattan distance between `{x, y}` and `{cx, cy}`;\n\t* check if `currDist < bestDist` and in case update both `bestDist` and `res` accordingly.\n\nOnce done, we can return `res` :)\n\nThe code:\n\n```cpp\nclass Solution {\npublic:\n    int nearestValidPoint(int x, int y, vector<vector<int>>& points) {\n        // support variables\n        int res = -1, bestDist = INT_MAX;\n        // parsing points\n        for (int i = 0, cx, cy, currDist, lmt = points.size(); i < lmt; i ++) {\n            // assigning cx and cy\n            cx = points[i][0], cy = points[i][1];\n            // looking for a match\n            if (x == cx || y == cy) {\n                // computing currDist and in case updating bestDist and res\n                currDist = abs(y - cy) + abs(x - cx);\n                if (currDist < bestDist) {\n                    bestDist = currDist, res = i;\n                }\n            }\n        }\n        return res;\n    }\n};\n```
['C', 'C++']