자료구조 공부/Hash

프로그래머스 해시 Level 1 (완주하지 못한 선수)

kdhoooon 2021. 4. 4. 18:46

문제


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

마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수들의 이름이 담긴 배열 completion이 주어질 때, 완주하지 못한 선수의 이름을 return 하도록 solution 함수를 작성해주세요.

 

제한사항

  • 마라톤 경기에 참여한 선수의 수는 1명 이상 100,000명 이하입니다.
  • completion의 길이는 participant의 길이보다 1 작습니다.
  • 참가자의 이름은 1개 이상 20개 이하의 알파벳 소문자로 이루어져 있습니다.
  • 참가자 중에는 동명이인이 있을 수 있습니다.

 

 

 

풀이


HashMap을 이용하여 해당 이름이 존재하면 value 값을 줄여주고 value 값이 0 이라면 key 값을 삭제해주는 방식으로 풀었다.

 

Level 1 문제인 만큼 HashMap의 메소드를 사용할 줄 아는가에 대한 문제였다.

 

<전체코드>

import java.io.*;
import java.util.*;

class Solution {
    public String solution(String[] participant, String[] completion) {
        StringBuilder answer = new StringBuilder();
        HashMap<String, Integer> hash = new HashMap<String,Integer>();
        
        for(int i = 0 ; i < participant.length ; i++){
            if(!hash.containsKey(participant[i])){
                hash.put(participant[i], 1);
            }
            else{
                int count = hash.get(participant[i]);                
                hash.put(participant[i], ++count);
            }
        }
        
        for(int i = 0 ; i < completion.length ; i++){
            if(hash.containsKey(completion[i])){
                int count = hash.get(completion[i]);
                if(count == 1){
                    hash.remove(completion[i]);
                }
                else{
                    hash.put(completion[i], --count);
                }
            }
        }
        
        for(String name : hash.keySet()){
            answer.append(name);
        }
        
        return answer.toString();
    }
}