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:
代码:
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
原文:https://www.cnblogs.com/zlrrrr/p/10336193.html