Programming Language/C, C++
[프로그래머스][Lv. 1] 완주하지 못한 선수 C++ 풀이
myungsup1250
2022. 3. 14. 15:36
https://programmers.co.kr/learn/courses/30/lessons/42576
코딩테스트 연습 - 완주하지 못한 선수
수많은 마라톤 선수들이 마라톤에 참여하였습니다. 단 한 명의 선수를 제외하고는 모든 선수가 마라톤을 완주하였습니다. 마라톤에 참여한 선수들의 이름이 담긴 배열 participant와 완주한 선수
programmers.co.kr
풀이
아주 어렵지는 않은 문제이다.
문제 링크에 들어가면 확인할 수 있는 "해시"에서 힌트를 얻어도 좋다.
완주한 선수 (completion) vector 배열을 iteration하여 map<string, int> 컨테이너 comp에 선수 이름을 추가한다.
선수 이름이 처음 추가되는 경우에는 1을, 기존에 동명이인이 있다면 기존 int 값을 1 더해준다.
그 후 참가자 (participant) vector 배열을 iteration하여 comp map 컨테이너에 선수 이름이 존재하는지 확인하는 작업을 수행하면 된다.
선수 이름 자체가 존재하지 않는 경우에는 그 선수의 이름을 바로 반환하면 되고,
선수 이름이 존재할 경우에는 int 값을 1 빼준 다음 0보다 작다면 그 이름을 반환하면 된다.
끝!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#include <string>
#include <vector>
#include <map>
using namespace std;
string solution(vector<string> participant, vector<string> completion) {
map<string, int> comp;
map<string, int>::iterator it_m;
vector<string>::iterator it_v;
for (it_v = completion.begin(); it_v != completion.end(); it_v++) {
if (comp.find(*it_v) == comp.end()) { // Not found
comp.insert(make_pair(*it_v, 1));
} else { // Found
comp[*it_v] += 1;
}
}
for (it_v = participant.begin(); it_v != participant.end(); it_v++) {
if ((it_m = comp.find(*it_v)) == comp.end()) { // Not found
return *it_v;
} else { // Found
it_m->second -= 1;
if (it_m->second < 0) {
return it_m->first;
}
}
}
return "";
}
|
cs |