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

 

코딩테스트 연습 - 완주하지 못한 선수

수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다. 마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수

programmers.co.kr

 


소스 코드

파이썬

def solution(participant, completion):
    answer = ''
    dictionary = {}
    for name in participant:
        if name not in dictionary: # 딕셔너리에 없는데 if dictionary[name]으로 조건문 주면 오류 남
            dictionary[name] = 1
        else:
            dictionary[name] += 1

    for name in completion:
        dictionary[name] -= 1

    for name in dictionary:
        if dictionary[name] != 0:
            answer = name

    return answer

 

자바스크립트

function solution(participant, completion) {
    var answer = '';
    var dictionary = {}

    for (name of participant) { // 배열의 값 for of로 순회
        if (dictionary[name] >= 0) { // dictionary[name]이 이미 존재한다면
            dictionary[name] += 1
        } else {
            dictionary[name] = 1
        }
    }

    for (name of completion) {
        dictionary[name] -= 1
    }

    for (name in dictionary) { // 딕셔너리의 key 값 for in으로 순회
        if (dictionary[name] != 0) {
            answer = name
            break
        }
    }

    return answer;
}

 

 

 


풀이 과정

{참가자 이름 : 해당 이름으로 미완주한 사람의 수} 딕셔너리를 활용해서 문제를 해결하였다.

 

completion 배열로 딕셔너리를 순회하며 해당 이름으로 미완주한 사람의 수를 1씩 줄여주고, 다시 딕셔너리를 순회하면서 해당 이름으로 미완주한 사람의 수가 1명 이상이면 그 사람의 이름을 정답으로 출력하면 된다.

+ Recent posts