[프로그래머스] 완주하지 못한 선수

Salki·2021년 2월 24일
0

알고리즘

목록 보기
5/10

프로그래머스 완주하지 못한 선수 문제

첫번째 코드

function solution(participant, completion) {
    var answer = '';
    for(var i = 0; i<completion.length; i++)
        {
            const idx = participant.indexOf(completion[i]);
            participant.splice(idx,1);
        }
    answer = participant[0];
    return answer;
}

완주한 선수를 참가자 중에서 찾은뒤 삭제해서 마지막 남은 선수만 리턴해주었다.
값은 나오나 시간초과로 실패.

두번째 코드

function solution(participant, completion) {
    var answer = '';
    
    let people = new Map();
    
    for(var i=0; i<participant.length; i++)
    {
        if(people.get(participant[i])>0)
        {
            let cnt = people.get(participant[i]);
            people.set(participant[i], cnt+1);
        }
        else
        {
            people.set(participant[i], 1);
        }
    }
    for(var i=0; i<completion.length; i++)
    {
        if(people.get(completion[i])>0)
        {
            let cnt = people.get(completion[i]);
            people.set(completion[i], cnt-1);
            if(cnt-1===0)
            {
                people.delete(completion[i]);        
            }
            
        }
    }
    for(let key of people.keys())
        {
            console.log(key);
            answer = key;
        }
    return answer;
}

map구조를 만들어서 참가자들 인원수를 카운트한 뒤 도착한 사람들을 -1 해주었다.
다른사람 풀이를 보니까 훨~씬 더 간단하여 참고해서 변경할 예정이다.

 const map = new Map();

    for(let i = 0; i < participant.length; i++) {
        let a = participant[i], 
            b = completion[i];

        map.set(a, (map.get(a) || 0) + 1);
        map.set(b, (map.get(b) || 0) - 1);
    }

    for(let [k, v] of map) {
        if(v > 0) return k;
    }

    return 'nothing';

비슷하지만 더 간단한 코드.

profile
실력있는 개발자로 거듭나기까지..

0개의 댓글