Leetcode 347. 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]
题目大意:给定一个非空整数数组,返回出现频率最高的k(1<=k<=n, n为数组元素总数)个元素。
解题思路1:
利用一个哈希表来存放每个元素和其出现次数的键值对,通过遍历一次数组nums完成。对该哈希表的键值对按照出现次数的从大到小进行排序,通过将所有键值对存放到一个pair类型的vector实现。将排序后的前k对键值对的键存入答案vector并返回。时间复杂度为O(nlogn).
代码:
class Solution {
static int comp(pair<int, int> &a, pair<int, int> &b)
{
return a.second > b.second;
}
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
int len = nums.size();
unordered_map<int, int> mp;
vector<int> res;
vector<pair<int, int>> st;
for(int i = 0; i < len; i++)
mp[nums[i]] += 1;
for(auto it = mp.begin(); it != mp.end(); it++)
if(it->second != 0)
st.push_back(*it);
sort(st.begin(), st.end(), comp);
for(int i = 0; i < k; i++)
{
res.push_back(st[i].first);
}
return res;
}
};
解题思路2:
对哈希表的排序可以使用另一种数据结构优先队列实现堆排序。代码更简洁但速度不如解法1的sort快排。
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> mp;
vector<int> res;
priority_queue<pair<int, int>> q;
for(auto key : nums)
mp[key]++;
for(auto it: mp)
q.push({it.second, it.first});
for(int i = 0; i < k; i++)
{
res.push_back(q.top().second);
q.pop();
}
return res;
}
};
本文深入解析LeetCode 347题——Top K Frequent Elements,探讨了两种高效算法策略:一是使用哈希表结合快速排序,二是采用优先队列实现堆排序。详细介绍了每种方法的实现步骤与代码示例,对比了它们的时间复杂度与实际运行效率。
869

被折叠的 条评论
为什么被折叠?



