347. Top K Frequent Elements

https://leetcode.com/problems/top-k-frequent-elements/description/

Given a non-empty array of integers, return the k most frequent elements.

For example,

Given [1,1,1,2,2,3] and k = 2, return [1,2].

Note:

You may assume k is always valid, 1 ≤ k ≤ number of unique elements.

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

Thoughts

找出现频率最高的K个元素。前x的k个=>heap。要求最大的k个,维持一个大小为k的min heap,每次遍历时当超过k个时,把最小的踢出去,剩下的的就是最大的K个。

Code

/*
 * @lc app=leetcode id=347 lang=cpp
 *
 * [347] Top K Frequent Elements
 */

// @lc code=start
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> freq;
        const auto cmp = [](auto &a, auto &b) {
            return a.first > b.first;
        };
        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pq(cmp);
        for (const auto num : nums) ++freq[num];
        for (const auto &p : freq) {
            pq.push({p.second, p.first});
            if (pq.size() > k) {
                pq.pop();
            }
        }
        vector<int> res(k, 0);
        for (int i = k - 1; i >= 0; --i) {
            res[i] = pq.top().second;
            pq.pop(); 
        }
        return res;
    }
};
// @lc code=end

Analysis

时间复杂度O(n + klgn).

Last updated

Was this helpful?