347. Top K Frequent Elements

Given an integer array nums and an integer k, return the k most frequent elements . You may return the answer in any order.

Example 1:

复制代码
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

复制代码
Input: nums = [1], k = 1
Output: [1]

Constraints:

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104
  • k is in the range [1, the number of unique elements in the array].
  • It is guaranteed that the answer is unique.

Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

复制代码
class Solution {
public:
    class mycomparision{
    public://别忘记加上
        bool operator()(const pair<int,int>&lhs,const pair<int,int>& rhs){//重载()运算符
            return lhs.second>rhs.second;
        }
    };
    vector<int> topKFrequent(vector<int>& nums, int k) {
        //统计元素出现频率
        unordered_map<int,int>map;
        for(int i=0;i<nums.size();i++){
            map[nums[i]]++;
        }
        //频率排序+定义小顶堆
        priority_queue<pair<int,int>,vector<pair<int,int>>,mycomparision>pri_que;
        //用固定大小为K的小顶堆扫描所有频率的大小
        for(unordered_map<int,int>::iterator it=map.begin();it!=map.end();it++){
            pri_que.push(*it);
            if(pri_que.size()>k){
                pri_que.pop();
            }
        }
        //找出前K个高频元素,由于小顶堆先弹出最小的,所以数组倒序,注意要从k-1开始
        vector<int> result(k);
        for (int i = k - 1; i >= 0; i--) {
            result[i] = pri_que.top().first;
            pri_que.pop();
        }
        return result;
    }
};
相关推荐
徐某人..30 分钟前
基于i.MX6ULL平台的智能网关系统开发
arm开发·c++·单片机·qt·物联网·学习·arm
无敌秋1 小时前
# C++ 简单工厂模式实战指南
c++·简单工厂模式
code_pgf1 小时前
Octo 算法详解-开源通用机器人策略模型技术报告
算法·机器人·开源
cany10001 小时前
C++ -- 模板的声明和定义
开发语言·c++
澈2071 小时前
深耕进阶 Day1:C 与 C++ 核心差异 + C++ 入门基石
c语言·开发语言·c++
嘻嘻哈哈樱桃1 小时前
牛客经典101题题解集--动态规划
java·数据结构·python·算法·职场和发展·动态规划
脱氧核糖核酸__2 小时前
LeetCode热题100——234.回文链表(两种解法)
c++·算法·leetcode·链表
IronMurphy2 小时前
【算法四十二】118. 杨辉三角 198. 打家劫舍
算法
电科一班林耿超2 小时前
第 16 课:动态规划专题(二)—— 子序列与子数组问题:面试最高频的 DP 题型
数据结构·算法·动态规划