얀에서는 매년 달리기 경주가 열립니다. 해설진들은 선수들이 자기 바로 앞의 선수를 추월할 때 추월한 선수의 이름을 부릅니다. 예를 들어 1등부터 3등까지 "mumu", "soe", "poe" 선수들이 순서대로 달리고 있을 때, 해설진이 "soe"선수를 불렀다면 2등인 "soe" 선수가 1등인 "mumu" 선수를 추월했다는 것입니다. 즉 "soe" 선수가 1등, "mumu" 선수가 2등으로 바뀝니다.
선수들의 이름이 1등부터 현재 등수 순서대로 담긴 문자열 배열 players와 해설진이 부른 이름을 담은 문자열 배열 callings가 매개변수로 주어질 때, 경주가 끝났을 때 선수들의 이름을 1등부터 등수 순서대로 배열에 담아 return 하는 solution 함수를 완성해주세요.
SourceCode
#include <string> #include <vector> #include <iostream> #include <algorithm> using namespace std; vector<string> solution(vector<string> players, vector<string> callings) { for(int i=0; i<callings.size(); i++) { int idx = find(players.begin(), players.end(), callings[i]) - players.begin(); swap(players[idx], players[idx-1]); } return players; }
→ 시간 초과 발생,,
#include <string> #include <vector> #include <map> #include <iostream> #include <algorithm> using namespace std; vector<string> solution(vector<string> players, vector<string> callings) { vector <string> answer; map <string, int> rank; // 순위 찾기 위한 map map <int, string> name; // 이름 찾기 위한 map for(int i=0; i<players.size(); i++) { rank.insert({players[i], i+1}); // 선수 이름, 등수 name.insert({i+1, players[i]}); // 등수, 선수 이름 } for(int i=0; i<callings.size(); i++) { int idx = rank[callings[i]]; // 추월 전 등수 string before = name[idx - 1]; // 추월할 선수 rank[callings[i]]--; rank[before]++; name[idx] = before; name[idx - 1] = callings[i]; } for (pair <int, string> str : name) { answer.push_back(str.second); } return answer; }
시간 복잡도
를 계산해보는 습관 가지기 !!!