GaGe

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

알고리즘/[2021] 프로그래머스

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

Sorrel 2021. 5. 30. 23:42
#include <string>
#include <vector>
#include <unordered_map>
 
using namespace std;
 
string solution(vector<string> participant, vector<string> completion) {
    string answer = "";
    unordered_map<string, int> strMap;
    for(auto elem : completion){
        if(strMap.end() == strMap.find(elem)) //만약 elem을 찾아서 끝이 보이면 추가한다.
            strMap.insert(make_pair(elem, 1));
        else //있다면 +1, 동명이인 두명
            strMap[elem]++;
    }
 
    for(auto elem : participant)
    {
        if(strMap.end() == strMap.find(elem)){ //만약 elem 을 찾는데 끝이 보였다면 없는 사람인것. 정답 도출
            answer = elem;
            break;
        }
        else{ //끝나기 전 elem을 찾았다면
            strMap[elem]-=1; //있으면 명수를 줄인다. 0이 정상
            if(strMap[elem] < 0){ //-1이 되면 동명이인 중에 완주 못한 사람이 정답.
                answer = elem;
                break;
            }
        }
    }
    
    return answer;
}

 

// 효율적인 코드

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

string solution(vector<string> participant, vector<string> completion) {
    string answer = "";
    sort(participant.begin(), participant.end());
    sort(completion.begin(), completion.end());
    for(int i=0;i<completion.size();i++)
    {
        if(participant[i] != completion[i])
            return participant[i];
    }
    return participant[participant.size() - 1];
    //return answer;
}
Comments