문제 설명
얀에서는 매년 달리기 경주가 열립니다. 해설진들은 선수들이 자기 바로 앞의 선수를 추월할 때 추월한 선수의 이름을 부릅니다. 예를 들어 1등부터 3등까지 "mumu", "soe", "poe" 선수들이 순서대로 달리고 있을 때, 해설진이 "soe"선수를 불렀다면 2등인 "soe" 선수가 1등인 "mumu" 선수를 추월했다는 것입니다. 즉 "soe" 선수가 1등, "mumu" 선수가 2등으로 바뀝니다.
선수들의 이름이 1등부터 현재 등수 순서대로 담긴 문자열 배열 players와 해설진이 부른 이름을 담은 문자열 배열 callings가 매개변수로 주어질 때, 경주가 끝났을 때 선수들의 이름을 1등부터 등수 순서대로 배열에 담아 return 하는 solution 함수를 완성해주세요.
의사코드
- map에 Key, Value 형태로 플레이어와 순위를 저장한다. (문자열로 순위를 탐색하기 위하여)
- 해설진들이 선수 이름을 부르면 선수 이름으로 순위를 찾는다.
- 해당 순위와 순위 -1에 해당하는 두 플레이어 이름을 벡터(players)에서 Swap한다.
코드 작성
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
void swap(string& playerA, string& playerB)
{
string temp = playerA;
playerA = playerB;
playerB = temp;
}
vector<string> solution(vector<string> players, vector<string> callings) {
for (string calling : callings)
{
auto it = find(players.begin(), players.end(), calling);
if (it != players.end())
{
swap(*it, *(--it));
}
}
return players;
}

벡터에서 선수 이름을 찾기 위해 find함수로 순차 탐색을 진행하다보니 실행 시간이 초과되었다.
코드 작성
#include <string>
#include <vector>
#include <map>
using namespace std;
vector<string> solution(vector<string> players, vector<string> callings) {
map<string, int> map1;
for (int idx = 0; idx < players.size(); ++idx)
{
map1[players[idx]] = idx;
}
for (string calling : callings)
{
int& callingPlayerNum = map1[calling];
string nextPlayer = players[callingPlayerNum - 1];
swap(map1[calling], map1[nextPlayer]);
swap(players[callingPlayerNum + 1], players[callingPlayerNum]);
}
return players;
}

'Algorithm > Practice' 카테고리의 다른 글
| [Algorithm] 공원 산책 (1) | 2025.01.20 |
|---|---|
| [Algorithm] 개인정보 수집 유효기간 (0) | 2025.01.17 |
| [Algorithm] 바탕화면 정리 (1) | 2025.01.15 |
| [Algorithm] 성격 유형 검사하기 (0) | 2025.01.15 |
| [Algorithm] 햄버거 만들기 (2) | 2025.01.14 |