日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

leetcode347. 前 K 个高频元素

發布時間:2023/12/4 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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;//創建map

2:插入數據

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 个高频元素的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。