개발/프로그래머스
해시 > 완주하지 못한 선수 (Level 1)
민돌이2
2021. 10. 28. 19:05
문제
수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다.
마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수들의 이름이 담긴 배열 completion이 주어질 때, 완주하지 못한 선수의 이름을 return 하도록 solution 함수를 작성해주세요.
제한사항
- 마라톤 경기에 참여한 선수의 수는 1명 이상 100,000명 이하입니다.
- completion의 길이는 participant의 길이보다 1 작습니다.
- 참가자의 이름은 1개 이상 20개 이하의 알파벳 소문자로 이루어져 있습니다.
- 참가자 중에는 동명이인이 있을 수 있습니다.
입출력 예
participant | completion | return |
["marina", "josipa", "nikola", "vinko", "filipa"] | ["josipa", "filipa", "marina", "nikola"] | "vinko" |
["mislav", "stanko", "mislav", "ana"] | ["stanko", "ana", "mislav"] | "mislav" |
["leo", "kiki", "eden"] | ["eden", "kiki"] | "leo" |
입출력 예 설명
예제 #1
"leo"는 참여자 명단에는 있지만, 완주자 명단에는 없기 때문에 완주하지 못했습니다.
예제 #2
"vinko"는 참여자 명단에는 있지만, 완주자 명단에는 없기 때문에 완주하지 못했습니다.
예제 #3
"mislav"는 참여자 명단에는 두 명이 있지만, 완주자 명단에는 한 명밖에 없기 때문에 한명은 완주하지 못했습니다.
소스 코드
#include <string>
#incldue <vector>
#include <unordered_map>
using namespace std;
string solutino(vector<string> participant, vector<string> completion)
{
string answer = "";
unordered_map<string, int> data;
//participant의 string값을 키값으로 넣고, value에 1대입
for (string part : participant)
data[part]++;
//participant가 들어가있는 map에 completion을 비교하여 존재한다면 value를 --하여 0으로 만듬
for (string comp : completion)
data[comp]--;
for (auto temp : data)
{
//map의 value가 1인 경우 completion에 존재하지 않다는 의미 -> 완주하지못했다.
if (temp.second == 1)
{
answer = temp.first;
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;
}
#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))
strMap.insert(make_pair(elem, 1));
else
strMap[elem]++;
}
for(auto elem : participant)
{
if(strMap.end() == strMap.find(elem))
{
answer = elem;
break;
}
else
{
strMap[elem]--;
if(strMap[elem] < 0)
{
answer = elem;
break;
}
}
}
return answer;
}
#include <string>
#include <vector>
#include <unordered_set>
using namespace std;
string solution(vector<string> participant, vector<string> completion) {
string answer = "";
unordered_multiset<string> names;
for(int i = 0; i < participant.size(); i++)
{
names.insert(participant[i]);
}
for(int i = 0; i < completion.size(); i++)
{
unordered_multiset<string>::iterator itr = names.find(completion[i]);
names.erase(itr);
}
return *names.begin();
}
728x90