Skip to content

Commit

Permalink
Add 0347-top-k-frequent-elements.c
Browse files Browse the repository at this point in the history
  • Loading branch information
seinlin committed Jan 11, 2023
1 parent afb94e9 commit 9f495e5
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions c/0347-top-k-frequent-elements.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// A structure to represent an element of the heap.
typedef struct {
int num;
int count;
} Heap;

static int compareHeap(const void* x, const void* y) {
return ((Heap*)y)->count - ((Heap*)x)->count;
}

/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* topKFrequent(int* nums, int numsSize, int k, int* returnSize){
int hash[20001] = {0};
Heap* heap;
int *res;
int i, j;
int c = 0;

for (i = 0; i < numsSize; i++) {
hash[nums[i]+10000]++;
if (hash[nums[i]+10000]) {
c++;
}
}

heap = (Heap*)malloc(sizeof(Heap) * c);
memset(heap, 0, sizeof(Heap) * c);

c = 0;
for (i = 0; i < 20001; i++) {
if(hash[i] > 0) {
heap[c].num = i - 10000;
heap[c].count = hash[i];
c++;
}
}
qsort(heap, c, sizeof(Heap), compareHeap);

c = 0;
res = (int*)malloc(sizeof(int) * k);
for (i = 0; i < k; i++) {
res[c++] = heap[i].num;
}

*returnSize = c;
return res;
}

0 comments on commit 9f495e5

Please sign in to comment.