Programmers 코딩테스트 고득점 Kit - 해시(Hash) 완주하지 못한 선수 C++

박준용·2022년 2월 26일
0
post-thumbnail

문제

코드

#include <string>
#include <vector>
#include <map>

using namespace std;

string solution(vector<string> participant, vector<string> completion) {
    string answer = "";
    map<string, int> map;
    for(string name: participant){
        map[name]++;
    }
    for(string name: completion){
        map[name]--;
    }
    for(auto i : map){
        if(i.second > 0){
            answer = i.first;
        }
    }
    return answer;
}

풀이
분류 자체가 hash를 활용하는 문제였기 때문에 map을 활용했다.

1. [이름 : 횟수] 를 저장할 map을 선언하고,
2. for문으로 map에 participant의 이름마다 1씩 증가하며 저장한다.
3. for문으로 map에서 completion의 이름마다 1씩 가감한다.
4. 완주하지 못한 선수의 이름의 hash는 0 이상의 숫자가 남아있기 때문에 if문으로 찾아낸다.

profile
경험을 좋아하는 개발자 박준용입니다.

0개의 댓글