/**
 * 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的题啊,呜呜呜。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。