欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode 347. Top K Frequent Elements

程序员文章站 2022-03-04 19:05:46
...

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Leetcode 347. Top K Frequent Elements

2. Solution

  • Version 1
bool compare(const pair<int, int> &a, const pair<int, int> &b) {
    return a.second > b.second;
}

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        map<int, int> elements;
        for(int i = 0; i < nums.size(); i++) {
            elements[nums[i]]++;
        }
        vector<pair<int, int>> temp;
        map<int, int>::iterator iter;
        for(iter = elements.begin(); iter != elements.end(); iter++) {
            temp.push_back(pair<int, int>(iter->first, iter->second));
        }
        sort(temp.begin(), temp.end(), compare);
        vector<int> result;
        for(int i = 0; i < k; i++) {
            result.push_back(temp[i].first);
        }
        return result;
    }

};
  • Version 2
class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        map<int, int> elements;
        for(int i = 0; i < nums.size(); i++) {
            elements[nums[i]]++;
        }
        vector<vector<int>> bucket(nums.size() + 1);
        map<int, int>::iterator iter;
        for(iter = elements.begin(); iter != elements.end(); iter++) {
            bucket[iter->second].push_back(iter->first);
        }
        reverse(bucket.begin(), bucket.end());
        vector<int> result;
        for(int i = 0; i < bucket.size(); i++) {
            for(int j = 0; j < bucket[i].size(); j++) {
                result.push_back(bucket[i][j]);
                if(result.size() == k) {
                    return result;
                }
            }
        }
        return result;
    }

};

Reference

  1. https://leetcode.com/problems/top-k-frequent-elements/description/
相关标签: Leetcode