07-28 18:23
Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
관리 메뉴

기록을 합시다.

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

공부/알고리즘

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

울집고양이세마리 2023. 6. 11. 23:27

문제 요약

  • 마라톤에 참여 하였지만 마라톤을 완주하지 못 한 사람을 구해야 한다.
  • 중복된 이름이 있어서 그 점을 유의해야 한다.
  • 문제에 나와있듯, 완주하지 못 한 사람은 딱 한 명이다.

내가 생각한 로직(python)

  • collections 라이브러리의 Counter 클래스를 사용하여, 완주한 사람과 완주하지 못 한 사람을 이름 별로 세어준 딕셔너리 생성
  • 딕셔너리들끼리 -연산을 한다. (python에서는 딕셔너리끼리 +, - 연산 가능)
  • 값이 0이 아닌 이름이 곧 정답

파이썬으로 제출한 정답

from collections import Counter

def solution(participant, completion):
    participant_dic = Counter(participant)
    completion_dic = Counter(completion)

    answer_dic = participant_dic - completion_dic
    for key in answer_dic.keys():
        if answer_dic[key] > 0:
            return key

내가 생각한 로직(java)

  • 참가자와 참가하지 않은 사람들의 Queue를 각각 만들어주고, 정렬 한다.
  • 참가하지 않은 사람의 Queue가 빌 때까지 Queue에서 poll을 해주고, 값을 비교한다.
  • 값이 서로 다를 때, 그 이름이 곧 정답이다.

자바로 제출한 정답

import java.util.*;

class Solution {
    public String solution(String[] participant, String[] completion) {
        LinkedList<String> participants = new LinkedList<String>(Arrays.asList(participant));
        LinkedList<String> completions = new LinkedList<String>(Arrays.asList(completion));

        Collections.sort(participants);
        Collections.sort(completions);

        String answer = "";

        while(!completions.isEmpty()){
            String participatedPerson = participants.poll();
            String completedPerson = completions.poll();

            if(!participatedPerson.equals(completedPerson)){
                answer=participatedPerson;
                break;
            }
        }
        if(answer==""){
            return participants.poll();
        }

        return answer;
    }
}
Comments