C++實(shí)現(xiàn)LeetCode(347.前K個(gè)高頻元素)
[LeetCode] 347. Top K Frequent Elements 前K個(gè)高頻元素
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
這道題給了我們一個(gè)數(shù)組,讓統(tǒng)計(jì)前k個(gè)高頻的數(shù)字,那么對于這類的統(tǒng)計(jì)數(shù)字的問題,首先應(yīng)該考慮用 HashMap 來做,建立數(shù)字和其出現(xiàn)次數(shù)的映射,然后再按照出現(xiàn)次數(shù)進(jìn)行排序??梢杂枚雅判騺碜?,使用一個(gè)最大堆來按照映射次數(shù)從大到小排列,在 C++ 中使用 priority_queue 來實(shí)現(xiàn),默認(rèn)是最大堆,參見代碼如下:
解法一:
class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> m; priority_queue<pair<int, int>> q; vector<int> res; for (auto a : nums) ++m[a]; for (auto it : m) q.push({it.second, it.first}); for (int i = 0; i < k; ++i) { res.push_back(q.top().second); q.pop(); } return res; } };
當(dāng)然,既然可以使用最大堆,還有一種可以自動(dòng)排序的數(shù)據(jù)結(jié)構(gòu) TreeMap,也是可以的,這里就不寫了,因?yàn)楦厦娴膶懛ɑ緵]啥區(qū)別,就是換了一個(gè)數(shù)據(jù)結(jié)構(gòu)。這里還可以使用桶排序,在建立好數(shù)字和其出現(xiàn)次數(shù)的映射后,按照其出現(xiàn)次數(shù)將數(shù)字放到對應(yīng)的位置中去,這樣從桶的后面向前面遍歷,最先得到的就是出現(xiàn)次數(shù)最多的數(shù)字,找到k個(gè)后返回即可,參見代碼如下:
解法二:
class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> m; vector<vector<int>> bucket(nums.size() + 1); vector<int> res; for (auto a : nums) ++m[a]; for (auto it : m) { bucket[it.second].push_back(it.first); } for (int i = nums.size(); i >= 0; --i) { for (int j = 0; j < bucket[i].size(); ++j) { res.push_back(bucket[i][j]); if (res.size() == k) return res; } } return res; } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/347
類似題目:
參考資料:
https://leetcode.com/problems/top-k-frequent-elements/
https://leetcode.com/problems/top-k-frequent-elements/discuss/81602/Java-O(n)-Solution-Bucket-Sort
到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(347.前K個(gè)高頻元素)的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)前K個(gè)高頻元素內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決codeblocks致命錯(cuò)誤:openssl/aes.h:沒有這樣的文件或目錄問題
這篇文章主要介紹了解決codeblocks致命錯(cuò)誤:openssl/aes.h:沒有這樣的文件或目錄問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06C語言實(shí)現(xiàn)五子棋對戰(zhàn)系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C語言實(shí)現(xiàn)五子棋對戰(zhàn)系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05VC++?2019?"const?char*"類型的實(shí)參與"LPCTSTR"
這篇文章主要給大家介紹了關(guān)于VC++?2019?"const?char*"類型的實(shí)參與"LPCTSTR"類型的形參不兼容的解決方法,文中通過圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2023-03-03