给定一个非空的整数数组,返回其中出现频率前 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 是数组的大小。
C++
class Solution {
public:
static bool compare(pair<int,int>& a, pair<int,int>& b)
{
return a.second>b.second;
}
vector<int> topKFrequent(vector<int>& nums, int k)
{
vector<int> res;
int n=nums.size();
map<int,int> tmp;
for(int i=0;i<n;i++)
{
tmp[nums[i]]++;
}
vector<pair<int,int>> vec;
for(auto it:tmp)
{
vec.push_back(make_pair(it.first,it.second));
}
sort(vec.begin(),vec.end(),compare);
for(int i=0;i<k;i++)
{
res.push_back(vec[i].first);
}
return res;
}
};
python
class Solution:
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
res=[]
n=len(nums)
dic={}
for i in range(n):
if nums[i] not in dic:
dic[nums[i]]=1
else:
dic[nums[i]]+=1
vec=[]
for key in dic:
vec.append([dic[key],key])
vec.sort()
num=len(vec)
for i in range(num-1,num-k-1,-1):
res.append(vec[i][1])
return res