347. Top K Frequent Elements

求数组中出现频率最高的前K个数
博客给出一道算法题,要求从非空整数数组中返回出现频率最高的前K个数,且算法时间复杂度要优于O(n log n)。解题思路是先统计每个数据的个数,再按出现次数排序,排序时需先将map数据存到vector,再用sort排序。

题目描述:

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

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.

解题思路:

先统计每个数据的个数,然后按出现次数进行排序,得到出现频率最高的前K个数。

在排序时需要注意要先将map中的数据保存到vector中,然后再使用sort进行排序。

代码:

 1 class Solution {
 2 public:
 3     vector<int> topKFrequent(vector<int>& nums, int k) {
 4         unordered_map<int, int> num_map;
 5         for (auto num : nums) 
 6             num_map[num]++;
 7         vector<int> ret;
 8         vector<pair<int, int> >tmp;
 9         ret.reserve(k);
10         tmp.reserve(num_map.size());
11         for (auto ite = num_map.begin(); ite != num_map.end(); ++ite) {
12             tmp.push_back(make_pair(ite->first, ite->second));
13         }
14         sort(tmp.begin(), tmp.end(),
15             [](const pair<int, int> &x, const pair<int, int> &y) -> int {
16             return x.second > y.second;
17         }); 
18         for (int i = 0; i < k; ++i) {
19             ret.push_back(tmp[i].first);
20         }
21         return ret;
22     }
23 };
View Code

 

转载于:https://www.cnblogs.com/gsz-/p/9546907.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值