[LeetCode] 1779. Find Nearest Point That Has the Same X or Y Coordinate

Chobby·5일 전
2

LeetCode

목록 보기
601/650

😎풀이

  1. 맨하튼 거리 조회 함수 정의
  2. points 순회
    2-1. xy 둘 다 일치하지 않는 경우 생략
    2-2. 맨하튼 거리가 최소 거리보다 큰 경우 생략
    2-3. 최소 거리와 인덱스 갱신
  3. 최소 거리에 해당하는 인덱스 반환
function nearestValidPoint(x: number, y: number, points: number[][]): number {
    let minDist = Infinity
    let minIdx = -1
    for(let i = 0; i < points.length; i++)  {
        const [px, py] = points[i]
        if(px !== x && py !== y) continue
        const curDist = getDistance(x, y, px, py)
        if(curDist >= minDist) continue
        minDist = curDist
        minIdx = i
    }
    return minIdx
};

function getDistance(x1: number, y1:number, x2:number, y2:number) {
    return Math.abs(x1 - x2) + Math.abs(y1 - y2)
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글