LeetCode: Find Nearest Point That Has The Same X Or Y Coordinate Solution
1/**2 * @param {number} x3 * @param {number} y4 * @param {number[][]} points5 * @return {number}6 */7var nearestValidPoint = function (x, y, points) {8 const calculateDist = (p1, p2) =>9 Math.abs(p1[0] - p2[0]) + Math.abs(p1[1] - p2[1])10 const validPointsWithIndex = points11 .map((point, i) => [point, i])12 .filter(([[pX, pY]]) => pX === x || pY === y)13 let min = Infinity14 let minIndex = -115 for (let i = 0; i < validPointsWithIndex.length; i++) {16 const dist = calculateDist(validPointsWithIndex[i][0], [x, y])17 if (dist < min) {18 min = dist19 minIndex = validPointsWithIndex[i][1]20 }21 }22 return minIndex23}
Comments
Loading comments...
Tags
leetcode
array
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.