[leetcode, JS] 2515. Shortest Distance to Target String in a Circular Array

mxxn·2024년 6월 2일
0

leetcode

목록 보기
169/198

문제

문제 링크 : Shortest Distance to Target String in a Circular Array

풀이

/**
 * @param {string[]} words
 * @param {string} target
 * @param {number} startIndex
 * @return {number}
 */
var closetTarget = function(words, target, startIndex) {
    let left = startIndex
    let right = startIndex
    let step = 0
    let n = words.length

    while(step <= n) { 
        if(words[left] === target || words[right] === target) {
            return step
        } else {
            right = (right + 1) % n
            left = (left -1 + n) % n
        }

        step++
    }

    return -1
};
  1. target이 나올때까지 left,right를 변경해가며 늘어난 step을 return하는 풀이
  • Runtime 46 ms, Memory 51.17 MB
profile
내일도 글쓰기

0개의 댓글