본문 바로가기
Study/Coding Test

[프로그래머스] 베스트앨범 Python, C++

by 들숨날숨흡 2023. 8. 1.
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/42579

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

(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