zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    P4890 Never·island
    P2617 Dynamic Rankings
    P3243 [HNOI2015]菜肴制作
    P4172 [WC2006]水管局长
    P4219 [BJOI2014]大融合
    P5241 序列
    P1501 [国家集训队]Tree II
    无法读取用户配置文件,系统自动建立Temp临时用户
    组件服务 控制台打不开
    打印服务器 功能地址保护错误
  • 原文地址:https://www.cnblogs.com/heyn1/p/11226203.html
Copyright © 2011-2022 走看看