realforceman 2021. 12. 19. 07:42
728x90

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

 

코딩테스트 연습 - 베스트앨범

스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다. 속한 노래가

programmers.co.kr

 

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