LeetCode - 347. 前 K 个高频元素

在这里插入图片描述
解法一:哈希表

typedef struct {
    int val;
    int cnt;
    UT_hash_handle hh;
}HashNode;

int cmp(HashNode *a, HashNode *b)
{
    return b->cnt - a->cnt;
}
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* topKFrequent(int* nums, int numsSize, int k, int* returnSize){
    HashNode *head = NULL;

    for (int i = 0; i < numsSize; i++) {
        HashNode *node = NULL;
        HASH_FIND_INT(head, &nums[i], node);
        if (node != NULL) {
            node->cnt++;
        } else {
            node = (HashNode *)malloc(sizeof(HashNode));
            node->val = nums[i];
            node->cnt = 1;
            HASH_ADD_INT(head, val, node);
        }
    }

    HASH_SORT(head, cmp);

    int *ans = (int *)malloc(k * sizeof(int));
    HashNode *curr = NULL;
    HashNode *next = NULL;
    int j = 0;
    HASH_ITER(hh, head, curr, next) {
        if (j < k) {
            ans[j++] = curr->val;
        }
    }

    *returnSize = k;
    return ans;
}

解法二:结构体模拟哈希映射

typedef struct{
    int value;
    int count;
}Data;

int NumCmp(const void *a, const void *b)
{
    int *aa = (int *)a;
    int *bb = (int *)b;
    return *aa - *bb; 
}

int NodeCmp(const void *a, const void *b)
{
    Data *aa = (Data *)a;
    Data *bb = (Data *)b;
    return bb->count - aa->count;
}

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* topKFrequent(int* nums, int numsSize, int k, int* returnSize){
    Data node[numsSize];
    
    qsort(nums, numsSize, sizeof(int), NumCmp);

    node[0].value = nums[0];
    node[0].count = 1;
    int index = 0;
    for (int i = 1; i < numsSize; i++) {
        if (nums[i] == nums[i - 1]) {
            node[index].count++;
        } else {
            node[++index].value = nums[i];
            node[index].count = 1;
        }
    }
    
    qsort(node, index + 1, sizeof(Data), NodeCmp);
    int *ans = (int *)malloc(numsSize * sizeof(int));
    for (int i = 0; i < k; i++) {
        ans[i] = node[i].value;
    }      
    *returnSize = k;

    return ans;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值