Leetcode hot 100

1 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]

vector<int> topKFrequent(vector<int>& nums, int k) {
    unordered_map<int,int> m;
    int max_count=0;
    for(int &p:nums){
        max_count=max(max_count,++m[p]);
    }
    vector<vector<int>> v(max_count+1);
    vector<int> answer;
    for(auto p:m)v[p.second].push_back(p.first);
    for(int i=max_count;i>=0;--i){
        for(int &p:v[i]){
            answer.push_back(p);
            if(--k==0)return answer;
        }
    }
    return answer;
}

你可能感兴趣的:(OJ刷题,leetcode,算法,面经,求职,后端)