728x90
https://school.programmers.co.kr/learn/courses/30/lessons/42579
(1) C++
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
using namespace std;
bool cmp1(pair<string, int> a, pair<string, int> b){
return a.second > b.second;
}
bool cmp2(pair<int, pair<string, int>> a, pair<int, pair<string, int>> b){
if (a.first == b.first){
return a.second.second < b.second.second;
}
else{
return a.first > b.first;
}
}
vector<int> solution(vector<string> genres, vector<int> plays) {
vector<int> answer;
map<string, int> map1;
vector<pair<int, pair<string, int>>> vec1;
for(int i = 0; i<genres.size(); i++){
map1[genres[i]] += plays[i];
vec1.push_back({plays[i], {genres[i], i}});
}
vector<pair<string, int>> vec2(map1.begin(), map1.end());
sort(vec2.begin(), vec2.end(), cmp1); //map -> vec2
sort(vec1.begin(), vec1.end(), cmp2);
for(int i = 0; i<vec2.size(); i++){
int count1 = 0;
for(int j = 0; j<vec1.size(); j++){
if (count1 == 2) break;
if(vec2[i].first == vec1[j].second.first){
count1 ++;
answer.push_back(vec1[j].second.second);
}
}
}
return answer;
}
(2) Python
def solution(genres, plays):
answer = []
genre_list = []
dict = {}
for g in range(len(genres)):
genre = genres[g]
if genre in dict:
dict[genre] += [[plays[g], g]]
else:
dict[genre] = [[plays[g], g]]
for genre in dict:
total = 0
dict[genre].sort(key = lambda x:(-x[0], x[1]))
for play in dict[genre]:
total += play[0]
genre_list.append([total, genre])
genre_list.sort(reverse = True)
for select in genre_list:
genre = select[1]
if len(dict[genre]) == 1:
answer.append(dict[genre][0][1])
else:
answer.append(dict[genre][0][1])
answer.append(dict[genre][1][1])
return answer
728x90
'Study > Coding Test' 카테고리의 다른 글
[프로그래머스] 배달 Python, C++ (0) | 2023.08.02 |
---|---|
[프로그래머스] 입국심사 Python, C++ (0) | 2023.08.01 |
[프로그래머스] 의상 Python, C++ (0) | 2023.08.01 |
[프로그래머스] K번째수 Python, C++ (0) | 2023.08.01 |
[프로그래머스] 게임 맵 최단거리 Python, C++ (0) | 2023.07.31 |