typedef struct {
int cnt;
char s[32];
}Word;
int cmp(void **a, void **b)
{
return (strcmp(*((char**)a), *((char**)b)));
}
int cmp1(Word *a, Word *b)
{
return (b->cnt - a->cnt);
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char ** topKFrequent(char ** words, int wordsSize, int k, int* returnSize){
int i;
int idx = 0;
Word *w = NULL;
char **res = NULL;
if (wordsSize == 0) {
*returnSize = 0;
return NULL;
}
if (wordsSize == 1) {
*returnSize = 1;
return words;
}
w = (Word*)malloc(wordsSize * sizeof(Word));
res = (char**)malloc(k * sizeof(char*));
for (i = 0; i < wordsSize; i++) {
w[i].cnt = 0;
w[i].s[0] = '\0';
}
qsort(words, wordsSize, sizeof(char*), cmp);
w[0].cnt = 1;
strcat(&w[0].s[0], words[0]);
for (i = 1; i < wordsSize; i++) {
if (strcmp(&w[idx].s[0], words[i]) == 0) {
w[idx].cnt++;
continue;
}
idx++;
w[idx].cnt = 1;
strcat(&w[idx].s[0], words[i]);
}
qsort(w, wordsSize, sizeof(Word), cmp1);
for (i = 0; i < k; i++) {
res[i] = (char*)malloc(32 * sizeof(char));
if (res[i] != NULL) {
res[i][0] = '\0';
strcat(res[i], w[i].s);
}
}
free(w);
*returnSize = k;
return res;
}
参考以上代码,将单词读入之后适配char ** words, int wordsSize,然后设置k=1,函数返回值即为所求
整体思路:统计-->降序排序-->取第一个单词