Skip to content
Rain Hu's Workspace
Go back

[Leetcode] 347. Top K Frequent Elements

Rain Hu

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:

Example 2:

Constraints:

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

二、分析

三、解題

1. Priority Queue

vector<int> topKFrequent(vector<int>& nums, int k) {
    unordered_map<int,int> freq;
    for (const int& num : nums)     // 統計每個數字出現的次數
        freq[num]++;
    priority_queue<pair<int,int>> pq;
    for (const auto& x : freq)      // 用 max_heap 裝 {頻率, 數字}
        pq.push(make_pair(x.second, x.first));
    vector<int> res;
    while (k--) {       // 取出現頻率前 k 高的
        res.push_back(pq.top().second);
        pq.pop();
    }
    return res;
}

2. Bucket Sort

vector<int> topKFrequent(vector<int>& nums, int k) {
    unordered_map<int,int> freq;
    for (const int& num : nums)     // 統計每個數字出現的次數
        freq[num]++;
    vector<vector<int>> bucket;
    for (const auto f : freq) {
        while (bucket.size() <= f.second) {     // 將數字,依不同頻率次數放到相對應的 vector 中
            bucket.push_back({});
        }
        bucket[f.second].push_back(f.first);
    }
    vector<int> res;
    for (int i = bucket.size()-1; i >= 0; i--) {
        for (int j = 0; j < bucket[i].size() && k; j++, k--) {      // 拿頻率前 k 多的元素
            res.push_back(bucket[i][j]);
        }
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[IT] SQL
Next
[Life] July's plan