#Leetcode# 347. Top K Frequent Elements
Posted 丧心病狂工科女
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#Leetcode# 347. Top K Frequent Elements相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/top-k-frequent-elements/
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.
代码:
class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int> mp; priority_queue<pair<int, int> > q; vector<int> ans; for(int i = 0; i < nums.size(); i ++) mp[nums[i]] ++; for(auto i : mp) q.push({i.second, i.first}); for(int i = 0; i < k; i ++) { ans.push_back(q.top().second); q.pop(); } return ans; } };
FHFHFH 说了还有时间复杂度更低的做法明天更
八个月快落
以上是关于#Leetcode# 347. Top K Frequent Elements的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 347. Top K Frequent Elements
Leetcode 347: Top K Frequent Elements
LeetCode OJ 347. Top K Frequent Elements hashmap+排序求解
leetcode347 - Top K Frequent Elements - medium