[JAVA]☕ | Easy and Explained Solution ❤ | Speed Beats 100% ✔️
Approach\n Describe your approach to solving the problem. \nThe solution involves a simple iteration of the array. \n\nAt each iteration we have to check if the
# Approach\n<!-- Describe your approach to solving the problem. -->\nThe solution involves a simple **iteration of the array**. \n\n*At each iteration* we have to check if **the point is valid**, in this case we have to check if the distance of this point is shorter than the distance that we found in previous iterations.\n\n**Note:** The initialization of sIndex and sDistance is higher than the *maximum value allowed by the input conditions*.\n \n# Complexity\n- **Time complexity:** $O(n)$\n- **Speed Beats:** 100%\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- **Space complexity:** $O(1)$\n- **Memory Beats:** 78.3%\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n    public int nearestValidPoint(int x, int y, int[][] points) {\n        \n        int sIndex = 100000;\n        int sDistance = 100000;\n\n        for (int i = 0; i < points.length; i++) {\n            \n            // Check if is a valid point\n            if (points[i][0] == x || points[i][1] == y) {\n\n                // Check if it is better than the previous best\n                int distance = Math.abs(x - points[i][0]) + Math.abs(y - points[i][1]);\n                if (sDistance > distance) {\n                    sDistance = distance;\n                    sIndex = i;\n                }\n            }\n        }\n\n        // Check if we have a valid point to return\n        if (sIndex == 100000)\n            return -1;\n        return sIndex;\n    }\n}\n```
['Array', 'Java']