본문 바로가기
Study or Lecture/항해 99클럽 코딩테스트 스터디

항해 99클럽 코딩테스트 스터디 11일차 TIL (비기너)

by yoondoo 2024. 11. 7.
728x90

<오늘의 학습 키워드>

- 해시

<오늘의 문제>

제목 : 프로그래머스 /  Lv1 / 42576. 완주하지 못한 선수

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

<풀이>

정답은 더보기

더보기
더보기
더보기
import java.util.*;

class Solution {
    
    private static Map<String,Integer> participantNames = new HashMap<>();
    private static Map<String,Integer> completionNames = new HashMap<>();
    
    public String solution(String[] participant, String[] completion) {
        String answer = "";

        for (int i=0; i < participant.length; i++) {
            if (!participantNames.containsKey(participant[i])) {
                participantNames.put(participant[i],1);
            } else {
                int count = participantNames.get(participant[i]);
                participantNames.put(participant[i], count + 1);
            }
        }

        for (int i=0; i < completion.length; i++) {
            if (!completionNames.containsKey(completion[i])) {
                completionNames.put(completion[i],1);
            } else {
                int count = completionNames.get(completion[i]);
                completionNames.put(completion[i], count + 1);
            }
        }

        for (String name : participantNames.keySet()) {
            if (!completionNames.containsKey(name)) {
                answer = name;
                break;
            } else if (!Objects.equals(participantNames.get(name), completionNames.get(name))) {
                answer = name;
                break;
            }
        }

        return answer;
    }
}

- Map에 각각의 참가자, 완주자 배열 목록을 순회하면서 <"이름", "동명이인 수">를 저장

- 참가자 Map에서 keySet 하나씩 순회하면서 완주자 Map를 비교한다.

- 1. 이름이 없으면 완주하지 못했기 때문에 정답

- 2. 이름은 있는데 동명이인 수가 다르면 동명이인 중 한사람이 완주하지 못 했기 때문에 정답

 

 

<결론, 주의할점>

- 해시맵을 한 개만 사용하고, getOrDefault(key, value) 메서드를 이용한 풀이가 있었다.

더보기
더보기
더보기
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);

 

반응형

댓글