---
# System prepended metadata

title: LeetCode - 47. Top K Frequent Elements
tags: [LeetCode]

---

---
title: LeetCode - 47. Top K Frequent Elements
tags: LeetCode
description: by cpp
---
# [LeetCode] 347. Top K Frequent Elements

input : 一個陣列和一個k值，
return : 陣列中前k個最常出現的值
```cpp=
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int> result;
        map<int, int> map1;
        // 計算各值數量
        for(int i:nums){
            map1[i]++;
        }
        // 先把他丟到2d的list中({次數,數字})，再透過出現次數排序
        list<list<int>> count;
        for(auto iter = map1.begin(); iter != map1.end(); iter++){
            // cout<<iter->first<<" "<<iter->second<<endl;
            count.push_back({iter->second,iter->first});
        }
        count.sort();
        //小->大 --> 大->小
        count.reverse();
        auto iter = count.begin();
        cout<<endl;
        for(int i = 0 ; i<k;i++){
            list<int> temp = *iter;
            //結果為第二個
            result.push_back(*(++temp.begin()));
            // cout<<*(++temp.begin());
            // cout<<endl;
            iter++;
        }
        
        return result;
    }
};
```

{%hackmd theme-dark %}