LeetCode-347 Top K Frequent Elements

题目描述

Given a non-empty array of integers, return the k most frequent elements.

 

题目大意

寻找数组中出现频率最高的前k个数字。

 

示例

E1

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

E2

Input: nums = [1], k = 1
Output: [1]

 

解题思路

LeetCode@sxycwzwzq主要思想是利用priority_queue保存数字以及其次数出现的频率,由于priority_queue能将存储类型按序排列,因此可以依次入队列,当队列中的数字内容多于unique number - k时,将队列顶部的元素存储。

 

复杂度分析

时间复杂度:O(N * log(N - K))

空间复杂度:O(N)

 

代码

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        map<int, int> unum;
        // 记录不同数字的出现频率
        for(int n : nums)
            unum[n]++;
        
        int thre = unum.size() - k;
        vector<int> res;
        priority_queue<pair<int, int> > ves;
        for(auto it = unum.begin(); it != unum.end(); ++it) {
            // 将数字的频率以及该数字入队列,注意pair的顺序
            ves.push(make_pair(it->second, it->first));
            // 若队列的数量多余thre,表示新加入的数字出现的频率较高
            if(ves.size() > thre) {
                res.push_back(ves.top().second);
                ves.pop();
            }
        }
        
        return res;
    }
};

 

转载于:https://www.cnblogs.com/heyn1/p/11226203.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值