排序和搜索----前 K 个高频元素

给定一个非空的整数数组,返回其中出现频率前 高的元素。

示例 1:

输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]

示例 2:

输入: nums = [1], k = 1
输出: [1]

说明:

  • 你可以假设给定的 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
  • 你的算法的时间复杂度必须优于 O(n log n) , 是数组的大小。

解答(C++):

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        // 构建map
        std::map<int, int> cmap;
        for (auto c : nums) {
            auto it = cmap.find(c);
            if (it == cmap.end()) {
                cmap.insert({c, 1});
            } else {
                cmap[c] = it->second + 1;
            }
        }
        
        vector<int> cvec;
        for (auto it : cmap) {
            cvec.push_back(it.first);
        }
        
        // 构建最小堆
        std::make_heap(cvec.begin(), cvec.end(), [&](const int& x, const int& y)->bool {
            return cmap[x] > cmap[y];
        });

        while (cvec.size() > k) {
            std::pop_heap(cvec.begin(), cvec.end(), [&](const int& x, const int& y)->bool {
                return cmap[x] > cmap[y];
            });
            cvec.pop_back();
        }
        
        return cvec;
    }
};

猜你喜欢

转载自www.cnblogs.com/vczf/p/12651497.html
今日推荐