본문 바로가기

problem solving

[프로그래머스]베스트앨범

map을 이용해 장르별 재생횟수를 측정한다.

map에서 측정된 장르별 재생횟수를 이용해 반복문을 작성한다.

매 순회마다 장르의 노래의 최대값의 위치를 구해서 answer에 추가해준다.

#include <string>
#include <vector>
#include <map>
#include <algorithm>
 
using namespace std;
 
vector<int> solution(vector<string> genres, vector<int> plays) {
    vector<int> answer;
    
    map<stringlong long> mainMap;
    vector<pair<intstring>> store;
    for(int idx = 0; idx < genres.size(); idx++) {
        mainMap[genres[idx]] += plays[idx];
        store.push_back( { plays[idx], genres[idx] });
    }
    
    vector<pair<intstring>> mapVal;
    for(auto it = mainMap.begin(); it != mainMap.end(); it++) {
        mapVal.push_back( { it->second, it->first });
    }
    
    sort(mapVal.begin(), mapVal.end(), greater<pair<intstring>>());
    
    for(int idx = 0; idx < mapVal.size(); idx++) {
        int max1 = 0, max2 = 0;
        int pos1 = 0, pos2 = 0;
        for(int i = 0; i < store.size(); i++) {
            if(store[i].second != mapVal[idx].second) { continue; }
            if(store[i].first > max1 || store[i].first > max2) {
                if(max2 >= max1) {
                    max1 = store[i].first; 
                    pos1 = i;
                }
                else {
                    max2 = store[i].first;
                    pos2 = i;
                }
            }
        }
        if(max2 > max1) { swap(pos1, pos2); }
        else if(max2 == max1 && pos1 > pos2) { swap(pos1, pos2); }
        answer.push_back(pos1);
        if(max2 == 0) { continue; }
        answer.push_back(pos2);
    }
    
    
    return answer;
}
cs

'problem solving' 카테고리의 다른 글

[프로그래머스]네트워크  (0) 2020.03.12
[프로그래머스]카펫  (0) 2020.03.12
[프로그래머스]위장  (0) 2020.03.12
[프로그래머스]구명보트  (0) 2020.03.11
[프로그래머스]괄호 변환  (0) 2020.03.10