-
[hash, vector] 프로그래머스 베스트 앨범알고리즘과 언어/c++ 2021. 8. 18. 15:32
알게된 점 :
1.
unordered_map<string, vector<pair<int, int>>> hashmap;
map의 키로 vector가 들어갈 수 있다는 점
2.
sum2.assign(sum.begin(), sum.end());
sort(sum2.begin(), sum2.end(), comp); //sum sortunordered_map 은 정렬할 수 없기 때문에 따로 벡터로 옮겨서 정렬한다.
#include <iostream> #include <string> #include <vector> #include <unordered_map> #include <algorithm> using namespace std; unordered_map<string, vector<pair<int, int>>> hashmap; unordered_map<string, int> sum; vector<pair<string, int>> sum2; bool comp(pair<string, int> a, pair<string, int> b) { return a.second > b.second; } bool comp2(pair<int, int> a, pair<int, int> b) { if(a.second == b.second) return a.first < b.first; //num return a.second > b.second; //count } vector<int> solution(vector<string> genres, vector<int> plays) { vector<int> answer; for(int i=0; i<genres.size(); i++) { hashmap[genres[i]].push_back(make_pair(i, plays[i])); //num, count sum[genres[i]] += plays[i]; //sum } sum2.assign(sum.begin(), sum.end()); sort(sum2.begin(), sum2.end(), comp); //sum sort for(int i=0; i<hashmap.size(); i++) { sort(hashmap[sum2[i].first].begin(), hashmap[sum2[i].first].end(), comp2); if(hashmap[sum2[i].first].size() == 1) answer.push_back(hashmap[sum2[i].first][0].first); else { answer.push_back(hashmap[sum2[i].first][0].first); answer.push_back(hashmap[sum2[i].first][1].first); } } return answer; } int main() { vector<string> genres = {"classic", "pop", "classic", "classic", "pop"}; vector<int> plays = {500, 600, 150, 800, 2500}; vector<int> rec; rec = solution(genres, plays); for(int i=0; i<rec.size(); i++) { cout << rec[i] << " "; } return 0; }
'알고리즘과 언어 > c++' 카테고리의 다른 글
C++) 백준 1780 종이의 개수 (0) 2022.02.08 C++) 원하는 자리수 까지 출력하기 (반올림, 올림, 내림) (0) 2022.02.07 ios_base::sync_with_stdio(false); cin.tie(NULL); (0) 2021.11.14 정규표현식 <regex> (0) 2021.09.20 최대값, 최소값 max_element min_element (프로그래머스 프린터) (0) 2021.08.19