leetcode347. 前 K 个高频元素/堆排

写在前面

这道题类似于昨晚腾讯的笔试题目,只不过腾讯的题目在此基础上又增加了前K个低频元素,看来多刷题还是有好处的。

题目:347. 前 K 个高频元素

给定一个非空的整数数组,返回其中出现频率前 k 高的元素。

示例 1:

输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]

示例 2:

输入: nums = [1], k = 1
输出: [1] 

提示:

  • 你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
  • 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
  • 题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的。
    你可以按任意顺序返回答案。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/top-k-frequent-elements
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

基本思想:两次map

  • 第一次可用unordered_map:以数组的元素作为键,元素的次数作为值
  • 第二次用map:一定要按键降序排列,以元素出现的次数作为键,以元素作为值,由于出现相同次数的元素可能有多个,因此将值定义成vector
class Solution {
    
    
public:
    
    vector<int> topKFrequent(vector<int>& nums, int k) {
    
    
        unordered_map<int, int> m;
        for(int i = 0; i < nums.size(); ++i){
    
    
            m[nums[i]]++;//值作为键
        }
        map<int, vector<int>, greater<int>> sm;//按照次数从大到小排
        for(auto temp : m){
    
    
            sm[temp.second].push_back(temp.first);//次数作为键
        }
        vector<int> res;
        int i = 0;
        while(i < k){
    
    
            for(auto temp : sm){
    
    
                for(int j = 0; j < temp.second.size() && i < k; ++j){
    
    
                    res.push_back(temp.second[j]);
                    ++i;
                }
                if(i >= k){
    
    
                    break;
                }
            }
        }
        return res;
    }
};


基本思想2:map+优先队列

  • unordered_map实现元素次数的统计
  • priority_queue实现将元素按照次数从大到小排列,需要自定义类型
class Solution {
    
    
public:
    struct Node{
    
    //自定义类型,元素,元素出现的次数
        int val, cnt;
        Node(int a, int b): val(a), cnt(b){
    
    }
        bool operator<(const Node& temp)const{
    
    //注意该函数的定义
            return cnt > temp.cnt;
        }
    };
    vector<int> topKFrequent(vector<int>& nums, int k) {
    
    
        //统计数组中每一个元素出现的次数
        unordered_map<int, int> m;
        for(int i = 0; i < nums.size(); ++i){
    
    
            m[nums[i]]++;//值作为键
        }
        
        priority_queue<Node, vector<Node>> pq;
        for(auto temp : m){
    
    
            if(pq.size() < k){
    
    //队列中的元素不足k个时,直接放入队列
                pq.push(Node(temp.first, temp.second));
            }
            else{
    
    //超过k个时,需要确定当前的和队头的大小关系
                if(temp.second > pq.top().cnt){
    
    
                    pq.pop();
                    pq.push(Node(temp.first, temp.second));                    
                }
            }
        }
        
        vector<int> res;
        while(!pq.empty()){
    
    
            res.push_back(pq.top().val);
            pq.pop();
        }
        
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_31672701/article/details/108451638
今日推荐