LeetCode 347. Top K Frequent Elements (Medium)

题目描述:

Given a non-empty array of integers, return the k most frequent elements.
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.

Example:

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

题目大意:给出一个数组和一个数字k,找出数组中前k个出现最多的数字。

思路:先哈希,键值对为(数字,出现次数),再对哈希表对进行桶排序,桶号为出现次数,桶内放的是数字,最后将排序结果输出即可。

c++代码:

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) 
    {
        map<int, int> myMap;
        vector<vector<int>> temp(nums.size() + 1);
        vector<int> ans;
        for (auto num : nums)
        {
            myMap[num]++;
        }
        for (auto h : myMap)
        {
            temp[h.second].push_back(h.first);
        }
        for (auto i = temp.size() - 1; i >= 0; i--)
        {
            for (auto x : temp[i])
            {
                ans.push_back(x);
                if (ans.size() == k) return ans;
            }
        }
        return ans;
    }
};

你可能感兴趣的:(LeetCode)