解法一:哈希表
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;
}