Top K Frequence Element

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.

Solution: Using priority Queue

This problem is quite similar to top frequent words, except that it doesn't require the order of it's elements. We can use a priority queue to keep track of the most frequent element.

Time complexity for push and pop queue are both O(N*logN) Space complexity is O(N)

    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> m;
        for (auto n: nums) m[n]++;

        priority_queue<pair<int, int>, vector<pair<int, int>>> q;
        for (auto it: m) {
            q.emplace(it.second, it.first);
        }

        vector<int> ans;
        while (k > 0) {
            ans.push_back(q.top().second);
            q.pop();
            k -= 1;
        }
        return ans;
    }

Solution: Using Bucket Sort

The idea is quite similar to bucket sort. We can use a bucket to store the count and the nuber arrays.

vector<int> topKFrequent(vector<int>& nums, int k) {
    unordered_map<int, int> freq;
    vector<vector<int>> bucket(nums.size()+1, vector<int>(0));

    for (auto num: nums) freq[num]++;
    for (auto it: freq) {
        bucket[it.second].push_back(it.first);
    }

    vector<int> ans;
    for (int i=bucket.size()-1; i >=0 && k > 0; i--) {
        for (auto num: bucket[i]) {
            ans.push_back(num);
            k -= 1;

            if (k == 0) break;
        }
    }

    return ans;
}

results matching ""

    No results matching ""