Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit591af37

Browse files
authored
Merge pull requestneetcode-gh#1994 from seinlin/347
Add 0347-top-k-frequent-elements.c
2 parentsa6fdcdc +9f495e5 commit591af37

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

‎c/0347-top-k-frequent-elements.c

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// A structure to represent an element of the heap.
2+
typedefstruct {
3+
intnum;
4+
intcount;
5+
}Heap;
6+
7+
staticintcompareHeap(constvoid*x,constvoid*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,intnumsSize,intk,int*returnSize){
15+
inthash[20001]= {0};
16+
Heap*heap;
17+
int*res;
18+
inti,j;
19+
intc=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+
returnres;
49+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp