코딩테스트/Programmers

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

grove1212 2025. 3. 13. 09:48

 

 

1. 내 풀이

정렬 후 다른 게 있으면 바로 리턴, 끝까지 다른게 안나오면 마지막 값 리턴

import java.util.*;

class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        Arrays.sort(participant);
        Arrays.sort(completion);
        
        for(int i = 0; i < completion.length ;i++) {
            if(!participant[i].equals(completion[i])){
                return participant[i];
            }
        }
        return participant[completion.length];
    }
}

 

 

 

2. 다른 분 풀이

HashMap을 이용하여 푸셨다. 둘다 원리는 같은 것 같다.

import java.util.HashMap;

class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        HashMap<String, Integer> hm = new HashMap<>();
        for (String player : participant) hm.put(player, hm.getOrDefault(player, 0) + 1);
        for (String player : completion) hm.put(player, hm.get(player) - 1);

        for (String key : hm.keySet()) {
            if (hm.get(key) != 0){
                answer = key;
            }
        }
        return answer;
    }
}