알고리즘

프로그래머스 Level 1 - 완주하지 못한 선수 (Javascript)

또롱또 2022. 5. 15. 09:49
728x90

https://programmers.co.kr/learn/courses/30/lessons/42576

function solution(participant, completion) {
    var answer = '';
    
    // 배열은 일단 정렬을 해준다
    let particiArr = participant.sort();
    let compleArr = completion.sort();
    
    // 전체 participant 배열을 돌면서 값이 없는걸 발견하면 
    for(let i=0; i<particiArr.length; ++i){
        if(particiArr[i] !== compleArr[i]){
            //그 값이 정답
            answer = particiArr[i];
            // 정답내보내기
            return answer;
        }
    }
}

가장 기본적으로 풀어냈다. 

정답코드는 해시를 이용해 푸는게 권장이기 때문에

해시로 푼걸 가져왔다.

 

function solution(participant, completion) {
const myMap = new Map();

    for ( const participant of participants){
        if(!myMap.get(participant)){
            myMap.set(participant, 1);
        }else{
            myMap.set(participant, myMap.get(participant)+1);
        }
    }

    for(const completion of completions){
        if(myMap.get(completion)){
            myMap.set(completion, myMap.get(completion)-1);
        }
    }
    
    for(const participant of participants){
        if(myMap.get(participant) && myMap.get(participant) >=1 ){
            answer = participant;
        }
    }
  }
728x90