[LeetCode] 1848. Minimum Distance to the Target Element

Chobby·4일 전
1

LeetCode

목록 보기
616/650

😎풀이

  1. 최소 거리 정의
  2. nums 순회
    2-1. target과 다르다면 생략,
    2-2. 현재 abs(i - start)의 값이 최솟값인지 비교 및 갱신
  3. 탐색된 최소 거리 반환환
function getMinDistance(nums: number[], target: number, start: number): number {
    let minDist = Infinity
    for(let i = 0; i < nums.length; i++) {
        if(nums[i] !== target) continue
        minDist = Math.min(minDist, Math.abs(i - start))
    }
    return minDist
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글