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

Add 0347-top-k-frequent-elements.c#1994

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
tahsintunan merged 1 commit intoneetcode-gh:mainfromseinlin:347
Jan 11, 2023
Merged
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletionsc/0347-top-k-frequent-elements.c
View file
Open in desktop
Original file line numberDiff line numberDiff 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;
}

[8]ページ先頭

©2009-2025 Movatter.jp