코딩테스트

[C++][해시] 프로그래머스 - 완주하지 못한 선수

goliot 2024. 3. 4. 17:07
반응형

 

참가자 중에는 동명이인이 있을수 있다에 주목했다.

 

중복된 원소가 필요하다는 뜻이므로 unordered_multiset을 사용했다.

 

완주자의 수가 항상 참가자의 수보다 1 작으므로, 단순하게 생각하여 모든 참가자의 해시테이블에서 완주자를 한명씩 제거해 나가면 완주하지 못 한 1명이 남을 것이다.

#include <string>
#include <vector>
#include <unordered_set>

using namespace std;

string solution(vector<string> participant, vector<string> completion) {
    string answer = "";
    unordered_multiset<string> us(participant.begin(), participant.end());
    
    for(int i=0; i<completion.size(); i++) {
        us.erase(us.find(completion[i]));
    }
    
    answer = *us.begin();
    
    return answer;
}

 

만약 원소를 지울 때, 단순히 us.erase(completion[i]);를 사용했다면, 중복된 모든 원소들이 다 지워진다.

위처럼 us.erase(us.find(completion[i]);를 사용한다면, 하나만 지워지게 되어 의도된 동작을 수행한다.

반응형