【leetcode】Top K Frequent Elements

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.

利用桶排序,分三步解决,时间代价O(n):
  • 统计每个数的出现频率,存在unordered_map中
  • 定义一个vector>容器,将每个频率对应的数存在vector中
  • 倒序遍历容器,依次将k个数存入结果容器中

class Solution {
public:
    vector topKFrequent(vector& nums, int k)
    {
        unordered_map dict;
        vector result;
        for (auto n : nums)
            ++dict[n];
        vector< vector > freq(nums.size() + 1);
        for (auto p : dict)
            freq[p.second].push_back(p.first);
        for (int i = freq.size() - 1; i >= 0 && result.size() < k; --i)
        {
            for (auto n : freq[i])
            {
                result.push_back(n);
                if (result.size() == k)
                    break;
            }
        }
        return result;
    }
};


你可能感兴趣的:(练习,算法,C++,STL)