[프로그래머스] lv1 달리기경주 시간초과
본문 바로가기

알고리즘

[프로그래머스] lv1 달리기경주 시간초과

이중for문에서 시간초과에러남

function solution(players, callings) {
    let copyArr = players
    function updatedArr(name){//'kai'
        for(let j = 0; j<copyArr.length; j++){
            if(copyArr[j] === name){
            let snapshot = copyArr[j-1]
            copyArr[j-1] = name
            copyArr[j] = snapshot
            return copyArr
        }
        }   
    }
    for(let i = 0; i<callings.length; i++){
         updatedArr(callings[i])
    }
    return copyArr;
}

시간초과 원인을 찾아보았다.

1. 배열 복제 - 메모리이용증가가 된다고해서 players를 복제한 copyArr을 사용하지않기로 수정

2. for문 - 이중 map으로 변경

function solution(copyArr, callings) {
    callings.map(e => {
        copyArr.map((j,idx) =>{
          if(j === e){
                let snapshot = copyArr[idx-1]
                copyArr[idx-1] = e
                copyArr[idx] = snapshot  
          }
            })
    })
    return copyArr;
}

 

오브젝트를 활용해보기로함

function solution(players, callings) {
    let obj = {}
    players.map((e,idx) => {
        obj[idx] = e
    })
    callings.forEach(e =>{
       let num = Object.values(obj).findIndex(i => i===e)
        let snapshot = obj[num - 1]
       obj[num - 1] = e
       obj[num] = snapshot
    })
    return Object.values(obj);
}

역시안됨 인터넷속도 문제일까?

 

끙끙거리다가 obj 2개로 해결됨

질문 게시글들을 보니 배열갯수가 엄청늘어날때를 가정하라고했는데

finxIndex함수도 결국 필터링을 거쳐야해서 이부분을 객체로 대체하기로함

function solution(players, callings) {
    let obj = {}
    let nameObj = {}
    players.map((e,idx) => {
        obj[idx] = e
        nameObj[e] = idx
    })
    callings.forEach(e =>{//'kai'
       // let num = Object.values(obj).findIndex(i => i===e)
        let num = nameObj[e]//3
        
        let snapshot = obj[num - 1]
       obj[num - 1] = e
       obj[num] = snapshot
        
        nameObj[e] = num - 1
        nameObj[snapshot] = num
        
    })
    return Object.values(obj);
}
반응형

'알고리즘' 카테고리의 다른 글

[백준 8959번] OX퀴즈 자바스크립트  (0) 2023.01.18