/**
* Note: The returned array must be malloced, assume caller calls free().
*/
typedef struct node{
int num;
int count;
}Hash;
void inset(Hash* hash,int size,int num){
int index=abs(num)%size;
if(hash[index].count==0){
hash[index].count++;
hash[index].num=num;
}else{
if(hash[index].num==num){
hash[index].count++;
}else{
while(hash[index].count!=0 && hash[index].num!=num) index=(index+1)%size;
hash[index].num=num;
hash[index].count++;
}
}
}
int cmp(const void* a,const void* b){
Hash* n1=(Hash*)a;
Hash* n2=(Hash*)b;
return n2->count-n1->count;
}
int* topKFrequent(int* nums, int numsSize, int k, int* returnSize) {
*returnSize=k;
Hash* hash=(Hash*)malloc(sizeof(Hash)*numsSize);
for(int i=0;i<numsSize;i++) hash[i].count=0;
for(int i=0;i<numsSize;i++){
inset(hash,numsSize,nums[i]);
}
qsort(hash,numsSize,sizeof(Hash),cmp);
int* array=(int*)malloc(sizeof(int)*k);
for(int i=0;i<k;i++){
array[i]=hash[i].num;
}
return array;
}
复试的时候一定要出个要自己写HASH的题啊,呜呜呜。
标签:count,index,num,int,元素,Hash,347,hash,高频 From: https://www.cnblogs.com/llllmz/p/18071443