出现频率最高的前 K 个元素
序号:#13 难度:有挑战 时间限制:1000ms 内存限制:10M
描述
有一个不为空且仅包含正整数的数组,找出其中出现频率最高的前 K 个数,时间复杂度必须在 O(n log n) 以内。
输入
一行数据包括两部分,一个正整数数组(数字间 ‘,’ 分隔)和一个正整数 K (1 ≤ K ≤ 数组长度),数组和 K 之间有一个空格。
输出
输出包含前 K 个出现频率最高的数(出现频率相同时,较小的数在前),用 ', ’ 分隔,保证升序排列。
输入样例
1,1,1,2,2,3 2
输出样例
1,2
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
struct node{
int s=0;
int y;
};
bool com(const node s1,const node s2)
{
if(s1.s>s2.s)
return true;
else
{
if(s1.s==s2.s)
{
if(s1.y<s2.y)
return true;
else
return false;
}
else
{
return false;
}
}
}
int main()
{
int n,cnt=0,x,i;
char t;
node a[200005];
cin>>x;
a[x].s++;
a[x].y=x;
while((t=getchar())!=' ')
{
cin>>x;
a[x].s++;
a[x].y=x;
}
cin>>n;
sort(a,a+200005,com);
for(i=0;i<n;i++)
{
cout<<a[i].y;
if(i!=(n-1))
{
cout<<",";
}
}
cout<<endl;
}