331.ベストアルバム


プログラマ


1. Python


from collections import Counter, defaultdict
def solution(genres, plays):
    answer = []
    n = len(genres)
    c = Counter()
    g = defaultdict(list)
    for i in range(n):
        c[genres[i]] += plays[i]
        g[genres[i]].append((plays[i], i))
        
    while(len(c) > 0):
        now = c.most_common(1)[0][0]
        temp = 0
        for i in sorted(g[now], key = lambda x: (-x[0], x[1])):
            answer.append(i[1])
            temp += 1
            if(temp == 2):
                break
        del c[now]   
    
    return answer

  

2. C++



#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>

using namespace std;

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

bool compare2(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;
    unordered_map<string,int> c;     
    unordered_map<string,vector<pair<int,int>>> g;                
    vector<pair<string,int>> v;                  
    
    for(int i=0; i < genres.size(); i++){
        c[genres[i]]+=plays[i];
        g[genres[i]].push_back({plays[i],i});
    }
    
    for(auto &k : g){
        sort(k.second.begin(),k.second.end(),compare);
    }
    v.assign(c.begin(),c.end());
    sort(v.begin(),v.end(),compare2);
    

    for(int i = 0; i < v.size(); i++){
        string now = v[i].first;
        for(int j = 0; (j < g[now].size() ) && (j < 2) ; j++){
            answer.push_back(g[now][j].second);
        }
    }
    return answer;
}

3. JavaScript


function solution(genres, plays) {
    const n = genres.length;
    let answer = [];
    let cnt = {};
    let list = {};
    
    for(let i = 0; i < n; i++){
        cnt[genres[i]] = (cnt[genres[i]] || 0) + plays[i];
        let arr = (list[genres[i]] || []);
        arr.push({plays: plays[i], index: i});
        list[genres[i]] = arr;
    }
    
    let rank = Object.keys(cnt).sort((a, b) => cnt[b] - cnt[a]);
    
    for(let i = 0; i < rank.length; i++){
        list[rank[i]].sort((a, b) => b.plays - a.plays);
        answer.push(list[rank[i]][0].index);
        answer.push(list[rank[i]][1].index);
    }
    return answer;
}