-
베스트앨범알고리즘 풀이/Programmers 2021. 12. 19. 07:42728x90
https://programmers.co.kr/learn/courses/30/lessons/42579
c++을 오랫만에 햇더니 낮설었다.
#include <iostream> #include <string> #include <vector> #include <unordered_map> #include <map> #include <algorithm> using namespace std; struct playCount { public: int index; int count; public: playCount(int index, int count) { this->index = index; this->count = count; } }; bool compare(std::pair<int, string> a, std::pair<int, string> b) { return a.first > b.first; } bool playCountCompare(playCount a, playCount b) { return a.count > b.count; } vector<int> solution(vector<string> genres, vector<int> plays) { std::unordered_map<string, std::vector<playCount>> genresHashMap; // unique genres order map int genresIdx = 0; for (std::string g : genres) { const auto v = genresHashMap.find(g); if (v != genresHashMap.end()) { v->second.push_back(playCount(genresIdx, plays.at(genresIdx))); } else { std::vector<playCount> indexVec; indexVec.push_back(playCount(genresIdx, plays.at(genresIdx))); genresHashMap.insert(std::make_pair(g, indexVec)); } ++genresIdx; } std::vector<std::pair<int, string>> genrePlayCountVec; // counts, genres idx for (auto g : genresHashMap) { const auto& indexVec = g.second; int genresPlayCountSum = 0; for (auto iv : indexVec) { const int playCounts = plays.at(iv.index); genresPlayCountSum += playCounts; } genrePlayCountVec.push_back(std::make_pair(genresPlayCountSum, g.first)); } // asc sort sort(genrePlayCountVec.begin(), genrePlayCountVec.end(), compare); std::vector<int> answer; const int MAX_GENRE = 2; // 장르 순서까지 모두 찾았으니 반환값을 생성한다. for (auto g : genrePlayCountVec) { const auto v = genresHashMap.find(g.second); // 제일 높은거 두개를 반환해야 한다. sort(v->second.begin(), v->second.end(), playCountCompare); int breakCondition = 0; for (auto a : v->second) { answer.push_back(a.index); breakCondition++; if (breakCondition == MAX_GENRE) { break; } } } return answer; }
728x90'알고리즘 풀이 > Programmers' 카테고리의 다른 글
다리를 지나는 트럭 (0) 2021.12.19 주식가격 (0) 2021.12.19 프린터 (0) 2021.12.19 기능개발 (0) 2021.12.19 위장 (0) 2021.12.19