본문 바로가기
Algorithm/Programmers

프로그래머스 42576번 완주하지 못한 선수

by eurowondollaryen 2022. 7. 16.

문제

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

풀이

1. participant의 내용은 completion의 내용을 포함하며, 1개 더 많다.

participant를 HashMap에 담고, completion으로 소거하는 방법을 쓰게 되면,

completion을 모두 소거 후, 찾는 과정이 생기게 되므로, completion을 HashMap에 담는다. (O(n-1))

2. participant를 순회하며, completionCount HashMap에서 탐색 및 소거시킨다.

2-1. 만약 count값이 이미 0이거나, null이면 완주하지 못한 선수이므로, 반환하면 된다.

 

import java.util.HashMap;
class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        HashMap<String, Integer> completionCount = new HashMap<String, Integer>();
        
        for(String name: completion) {
            if(completionCount.get(name) != null) {
                completionCount.put(name, completionCount.get(name) + 1);
            } else {
                completionCount.put(name, 1);
            }
        }
        for(String name: participant) {
            if(completionCount.get(name) != null && completionCount.get(name) != 0) {
                completionCount.put(name, completionCount.get(name) - 1);
            } else {
                answer = name;
                break;
            }
        }
        return answer;
    }
}