프로그래머스 베스트앨범

조항주·2022년 4월 19일
0

algorithm

목록 보기
27/50
post-thumbnail

문제

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

코드

#include <string>
#include <vector>
#include <map>
#include <algorithm>

using namespace std;

bool compare(pair<string,int> a,pair<string,int> b){
    return a.second>b.second;
}

vector<int> solution(vector<string> genres, vector<int> plays) {
    vector<int> answer;
    
    map<string,int> hash;
    map<string,pair<int,int>> firstValue;
    map<string,pair<int,int>> secondValue;
    
    for(int i=0;i<genres.size();i++){
        string genre=genres[i];
        
        hash[genre]+=plays[i];
        if(firstValue[genre].first==0) {
            firstValue[genre].first=plays[i];
            firstValue[genre].second=i;          
        }
        else{
            if(firstValue[genre].first<plays[i]||
               (firstValue[genre].first==plays[i]&&firstValue[genre].second>i)){
                secondValue[genre].first=firstValue[genre].first;
                secondValue[genre].second=firstValue[genre].second;
                firstValue[genre].first=plays[i];
                firstValue[genre].second=i;               
            }
            else if(firstValue[genre].first>=plays[i]){
                if(secondValue[genre].first<plays[i]
                   ||(secondValue[genre].first==plays[i]&&secondValue[genre].second>i)
                  ||(firstValue[genre].first==plays[i]&&firstValue[genre].second<i)){
                    secondValue[genre].first=plays[i];
                    secondValue[genre].second=i;                     
                }
            }           
        }     
    }
    vector<pair<string,int>> copy(hash.begin(),hash.end());
   
    sort(copy.begin(),copy.end(),compare);
    
    for(auto i:copy){
        answer.push_back(firstValue[i.first].second);
        if(secondValue[i.first].first!=0) answer.push_back(secondValue[i.first].second);
    }
    return answer;
}

풀이

로직은 안어려운데 구현이 생각보다 어려웠습니다. 해시테이블을 하나 만들어놓고 음악의 장르별로 재생횟수를 카운팅 합니다 그 뒤에 해시테이블을 정렬하려고 했는데 map은 정렬이 안되서 vector로 복사해서 정렬했습니다
장르별로 제일 큰값과 두번째값을 인덱스와 함께 업데이트 해주는거에요

0개의 댓글