LeetCode: Find Nearest Point That Has The Same X Or Y Coordinate Solution

1/**
2 * @param {number} x
3 * @param {number} y
4 * @param {number[][]} points
5 * @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 = points
11 .map((point, i) => [point, i])
12 .filter(([[pX, pY]]) => pX === x || pY === y)
13 let min = Infinity
14 let minIndex = -1
15 for (let i = 0; i < validPointsWithIndex.length; i++) {
16 const dist = calculateDist(validPointsWithIndex[i][0], [x, y])
17 if (dist < min) {
18 min = dist
19 minIndex = validPointsWithIndex[i][1]
20 }
21 }
22 return minIndex
23}

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.

Next Post

LeetCode: Design Hashmap

Mar 8, 2021

HoningJS

Search Posts