leetcode347. 前 K 个高频元素
生活随笔
收集整理的這篇文章主要介紹了
leetcode347. 前 K 个高频元素
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一:題目
二:上碼
class Solution { public:vector<int> topKFrequent(vector<int>& nums, int k) {unordered_map<int,int> m; //我們選用unordered_map 是因為其底層實現是哈希表,那么其//增刪效率和查詢效率較高unordered_map<int,int>:: iterator mt; multimap<int,int>mm;//這個容器中的key值不去重,其他的用法跟map一致multimap<int,int>:: reverse_iterator mmt;vector<int> ans;for(int i = 0; i < nums.size(); i++) {m[nums[i]]++;}for(mt = m.begin(); mt != m.end(); mt++) {int a = mt->second;int b = mt->first;mm.insert(make_pair(a,b));//將每個key值和其個數放入一個//不去重的 新的容器中(并將個數)} //作為新的key值for(mmt = mm.rbegin(); mmt != mm.rend(); mmt++) {if(k != 0){ans.push_back(mmt->second);k--;}}return ans;} };三:關于multimap的使用
1:初始化
multimap<string, int> mapStudent;//創建map2:插入數據
mapStudent.insert(pair<string, int>("student_one", 22)); mapStudent.insert(pair<string, int>("student_two", 25)); mapStudent.insert(pair<string, int>("student_three", 21));或者使用make_pair map<string, int> mapStudent; mapStudent.insert(make_pair("student_one", 22)); mapStudent.insert(make_pair("student_two", 25)); mapStudent.insert(make_pair("student_three", 21));3:遍歷容器
(1):正向的遍歷
//使用前向迭代器遍歷map map<string, int>::iterator iter; for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)cout << iter->first << " " << iter->second << endl;(2):逆向的遍歷
map<string, int>::reverse_iterator iter; for (iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++)cout << iter->first << " " << iter->second << endl; //反向遍歷(3):針對正向遍歷 可以不用迭代器 可以用 auto 關鍵字
for (auto it = mapStudent.begin(); it != mapStudent.end(); it++)cout << it->first << " " << it->second << endl; //遍歷如有疑問 請留言!!! 一個人走的很快 但團結協作走的更遠
總結
以上是生活随笔為你收集整理的leetcode347. 前 K 个高频元素的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 自动安装需要的模块包自动安装需要的模块包
- 下一篇: leetcode144. 二叉树的前序遍