LeetCode-347. Top K Frequent Elements [C++][Java]

LeetCode-347. Top K Frequent Elementsicon-default.png?t=M1H3https://leetcode.com/problems/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]

解题思路

【C++】

1. map + vector sort

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int,int> um;
        vector <int> res;
        for (int i=0;i<nums.size();i++) um[nums[i]]++;
        vector<pair<int,int>> freq_arr(um.begin(), um.end()); 
        sort(freq_arr.begin(),freq_arr.end(),compare); 
        for (int i = 0; i<k; i++) res.push_back(freq_arr[i].first);
        return res;
    }

    static bool compare(pair<int, int> p1, pair<int, int> p2) { 
        if (p1.second == p2.second) return p1.first > p2.first; 
		return p1.second > p2.second;     
    }
};

2. priority_queue + map

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        auto cmp = [](const pair<int,int>& p1, const pair<int,int>& p2) {
            return p1.second > p2.second;
        };
        priority_queue<pair<int,int>, vector<pair<int,int>>, decltype(cmp)> q(cmp);
        unordered_map<int, int> m;
        for (int i : nums) m[i]++;
        for (auto& p : m) {
            if (q.size() < k) q.push(p);
            else {
                if (cmp(q.top(), p)) continue;
                q.push(p);
                q.pop();
            }
        }
        vector<int> results;
        for (; !q.empty(); results.push_back(q.top().first), q.pop());
        return results;
    }
};

3. 桶排序

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> counts;
        int max_count = 0;
        for (const int & num : nums) {max_count = max(max_count, ++counts[num]);}
        vector<vector<int> > buckets(max_count + 1);
        for (const auto & p : counts) {buckets[p.second].push_back(p.first);}
        vector<int> res;
        for (int i = max_count; i >= 0 && res.size() < k; --i) {
            for (const int & num : buckets[i]) {
                res.push_back(num);
                if (res.size() == k) {break;}
            }
        }
        return res;
    }
};

【Java】

1. HashMap + PriorityQueue

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer,Integer> map= new HashMap<>();
        for (int a: nums) {map.put(a, map.getOrDefault(a, 0) + 1);}
        PriorityQueue<Map.Entry<Integer, Integer>> queue =
            new PriorityQueue<>((a,b) -> b.getValue() - a.getValue());
        for (Map.Entry<Integer, Integer> entry: map.entrySet()){queue.offer(entry);}
        int[] result = new int[k];
        for (int i=0; i<k; i++) {result[i] = queue.remove().getKey();}
        return result;
    }
}

2. 桶排序

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int maxCount = 0;
        for (int i=0; i<nums.length; i++) {
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
            maxCount = Math.max(maxCount, map.get(nums[i]));
        }
        List<Integer>[] bucket = new List[maxCount + 1];
        for (int e: map.keySet()) {
            int freq = map.get(e);
            if(bucket[freq] == null) {bucket[freq] = new ArrayList<>();}
            bucket[freq].add(e);
        }
        int[] ans = new int[k];
        int count = 0;
        for (int i=maxCount; i >= 0 && count < k; i--) {
            if (bucket[i] == null) {continue;}
            for (int num : bucket[i]) { 
                ans[count++] = num;
                if(count == k) break;
            }
        }
        return ans;                   
    }
}

参考文献

【1】PriorityQueue的用法和底层实现原理_Hanniboo's Blog-CSDN博客_priorityqueue

【2】你应该知道的 PriorityQueue ——深入浅出分析 PriorityQueue_Java极客技术-CSDN博客

【3】C++中priority_queue理解与使用_不积跬步无以至千里-CSDN博客_c++ priority_queue

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贫道绝缘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值