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

示例 1:

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

示例 2:

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

说明:

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

思路分析:先使用map将元素与其出现的次数关联,然后将其转化为pair放入vector容器按照出现的次数进行排序。再从vector容器中读出前k个元素即可。(时间复杂度为O(n log2n))

class Solution {
public:
    //自定义排序方式,根据second(元素出现的次数)的大小排序(从大到小,降序
    static bool cmp(pair<int, int> &one, pair<int, int> &two){
        return one.second > two.second;
    }
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> myMap;//用于将元素与元素出现的次数关联
        for (auto num : nums){
            myMap[num] += 1;
        }
        vector<pair<int, int>> myVec;//first表示的元素,second表示的出现的次数
        //将map里的键值对转换为pair
        for (auto it : myMap){
            myVec.push_back({it.first, it.second});
        }
        sort(myVec.begin(), myVec.end(), cmp);//自定义排序,根据second,元素出现的次数
        vector<int> result;
        //从myVec读出前k个元素的first的即可
        for (int i = 0; i < k; ++i){
            result.push_back(myVec[i].first);
        }
        return result;
    }
};

LeetCode 前K个高频元素
当然也可以使用内置的priority_queue

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<int> result;
		unordered_map<int, int> myMap;//用于将元素与元素出现的次数关联
		for (int i = 0; i < nums.size(); i++) 
            myMap[nums[i]]++;
		priority_queue<std::pair<int, int> > Q;//默认是按照pair的second降序
		for (auto i = myMap.begin(); i != myMap.end(); i++) 
            Q.push({ i->second, i->first });
        //然后读出优先队列的前k个
		for (auto i = 0; i < k; i++) {
			result.push_back(Q.top().second);
			Q.pop();
		}
		return result;
    }
};

相关文章:

  • 2022-12-23
  • 2022-03-09
  • 2021-12-04
  • 2021-07-06
  • 2021-08-07
  • 2018-11-13
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-05-18
  • 2021-06-06
  • 2022-12-23
  • 2022-01-01
  • 2021-08-03
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案