/**
* Note: The returned array must be malloced, assume caller calls free().
*/
typedef struct node{
int num;
int count;
}HASH;
void insert(HASH* h,int n,int size){
int index=abs(n)%size;
if(h[index].count==0 || h[index].num==n){
h[index].count++;
h[index].num=n;
}else{
while(h[index].count!=0 && h[index].num!=n) index=(index+1)%size;
h[index].num=n;
h[index].count++;
}
}
int cmp( const void* a,const void* b ){
HASH* x=(HASH*)a;
HASH* y=(HASH*)b;
if(x->count > y->count) return -1;
return 1;
}
int* topKFrequent(int* nums, int numsSize, int k, int* returnSize) {
HASH* h=(HASH*)malloc(sizeof(HASH)*numsSize);
for(int i=0;i<numsSize;i++) h[i].count=0;
for(int i=0;i<numsSize;i++){
insert(h,nums[i],numsSize);
}
qsort(h,numsSize,sizeof(HASH),cmp);
for(int i=0;i<numsSize;i++) printf("%d ",h[i].num);
*returnSize=k;
int* array=(int*)malloc(sizeof(int)*k);
for(int i=0;i<k;i++){
array[i]=h[i].num;
}
return array;
}
标签:count,index,HASH,int,元素,num,347,高频,size From: https://www.cnblogs.com/llllmz/p/18084770