Skip to content

Commit 591af37

Browse files
authored
Merge pull request #1994 from seinlin/347
Add 0347-top-k-frequent-elements.c
2 parents a6fdcdc + 9f495e5 commit 591af37

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Diff for: c/0347-top-k-frequent-elements.c

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// A structure to represent an element of the heap.
2+
typedef struct {
3+
int num;
4+
int count;
5+
} Heap;
6+
7+
static int compareHeap(const void* x, const void* y) {
8+
return ((Heap*)y)->count - ((Heap*)x)->count;
9+
}
10+
11+
/**
12+
* Note: The returned array must be malloced, assume caller calls free().
13+
*/
14+
int* topKFrequent(int* nums, int numsSize, int k, int* returnSize){
15+
int hash[20001] = {0};
16+
Heap* heap;
17+
int *res;
18+
int i, j;
19+
int c = 0;
20+
21+
for (i = 0; i < numsSize; i++) {
22+
hash[nums[i]+10000]++;
23+
if (hash[nums[i]+10000]) {
24+
c++;
25+
}
26+
}
27+
28+
heap = (Heap*)malloc(sizeof(Heap) * c);
29+
memset(heap, 0, sizeof(Heap) * c);
30+
31+
c = 0;
32+
for (i = 0; i < 20001; i++) {
33+
if(hash[i] > 0) {
34+
heap[c].num = i - 10000;
35+
heap[c].count = hash[i];
36+
c++;
37+
}
38+
}
39+
qsort(heap, c, sizeof(Heap), compareHeap);
40+
41+
c = 0;
42+
res = (int*)malloc(sizeof(int) * k);
43+
for (i = 0; i < k; i++) {
44+
res[c++] = heap[i].num;
45+
}
46+
47+
*returnSize = c;
48+
return res;
49+
}

0 commit comments

Comments
 (0)