Top K Frequent Elements解题报告

https://leetcode.com/problems/top-k-frequent-elements/

这道题的意思是选择出现频率前k位的元素,开始我想的是选择排序,后来发现,选择排序是找第k大元素的方法==。

一般来说求数组出现频率最高的数字都要用map来记录数字出现的频率,然后按照出现次数再次排序。这里可以用堆排序做。所以现在要复习一下堆排序了:
堆,可以看做是一棵完全二叉树,因为完全二叉树除了最底层之外,其他层都是满的。所以堆可以用数组表现出来。

对于给定某节点的坐标i:
parent=i
left=2i
right=2i+1
二叉堆一般分为两种:最大堆和最小堆。最大堆是最大的元素在根节点,最小堆是最小的元素在根节点。

实现堆排序首先需要实现,以第i个节点为根把原始数列调整成一个大顶堆,但是这里的调整不是一次到位,而是使第i个节点成为第i个节点到数组末的这部分数组中最大的数。

void Adjust(int k[],int i,int n){
int j;
int temp=k[i];
j=2*i;
while(j<=n){
if(j<n&&k[j]<k[j+1]) j++;
if(temp>k[j]) break;
k[j/2]=k[j];
j=2*j;
}
k[j/2]=temp;
}
这一次相当于会选出i到n中最大的数,然后将这个重复n次就可以了。

void heapSort(int k[],int n){
int i;
int temp;
for(i=n/2;i>=0;i--) Adjust(k,i,n);
for(i=n-1;i>=1;i--){
temp=k[i+1];
k[i+1]=k[1];
k[1]=temp;
Adjust(k,1,i);
}
}
这道题可以用优先队列:

,优先队列在C++中的解释是:
Priority queues are a type of container adaptors, specifically designed such that its first element is always the greatest of the elements it contains, according to some strict weak ordering criterion.This context is similar to a heap, where elements can be inserted at any moment, and only the max heap element can be retrieved (the one at the top in the priority queue).Priority queues are implemented as container adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are popped from the "back" of the specific container, which is known as the top of the priority queue.

代码:

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int> res;
        if(nums.size()==0) return res;
        unordered_map<int,int> mp;
        priority_queue<pair<int,int>> q;
        for(int i=0;i<nums.size();i++){
            if(mp.find(nums[i])==mp.end()) mp.insert(pair<int,int>(nums[i],1));
            else mp[nums[i]]++;
        }
        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;
    }
};




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值