728x90
반응형
🔗 문제 링크
https://school.programmers.co.kr/learn/courses/30/lessons/42579
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
반응형
728x90
👩💻 코드
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
using namespace std;
vector<int> solution(vector<string> genres, vector<int> plays) {
vector<int> answer;
map<string, int> count;
map<string, vector<pair<int, int>>> list;
for(int i=0; i<genres.size(); i++){
count[genres[i]] += plays[i];
list[genres[i]].push_back({i, plays[i]});
}
vector<pair<string, int>> genreOrder(count.begin(), count.end());
sort(genreOrder.begin(), genreOrder.end(), [](const pair<string, int>& a, const pair<string, int>& b) {
return a.second > b.second;
});
for(const auto& genre : genreOrder) {
string genreName = genre.first;
auto& songs = list[genreName];
sort(songs.begin(), songs.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
return a.second > b.second;
});
for (int i = 0; i < songs.size() && i < 2; i++) {
answer.push_back(songs[i].first);
}
}
return answer;
}
📝 풀이
장르를 key값으로 두 개의 map을 생성해 총 재생수와 장르의 노래 정보를 저장합니다.
장르의 재생수에 따라 내림차순으로 정렬하여 vector에 저장합니다.
각 장르마다 저장된 노래 정보를 재생수에 따라 내림차순으로 정렬합니다.
정렬된 후 상위 두 곡 고유 번호를 answer에 추가합니다.
만약 한 곡만 존재한다면 한 곡의 고유 번호만 추가합니다.
최종적으로 곡의 고유 번호를 담고 있는 answer을 return 합니다.
728x90
반응형
'코딩테스트 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 순위 (0) | 2024.10.26 |
---|---|
[프로그래머스] 단속카메라 (1) | 2024.10.25 |
[프로그래머스] 도둑질 (0) | 2024.10.25 |
[프로그래머스] 등굣길 (2) | 2024.10.24 |
[프로그래머스] 정수 삼각형 (0) | 2024.10.24 |