1. 题目描述
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/top-k-frequent-elements
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.代码如下
(1)//2019/04/20 使用链表建立hash链表
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
//使用链表动态实现hash表
typedef struct hashnode2
{
int value;//出?现?的??值??
int count;//出?现?的??次??数?y
struct hashnode2 *pnext;
}node;
node *findhashnode(node* listhead,int value)
{
node *ptemp = listhead;
while(ptemp != NULL)
{
if(ptemp->value == value)
{
return ptemp;
}
ptemp = ptemp->pnext;
}
return NULL;
}
void CreatehashList(node **pplisthead,int value)
{
node *listhead = *pplisthead;
node *temp = NULL;
if(listhead != NULL)
{
temp = findhashnode(*pplisthead,value);
if(temp!=NULL)
{
temp->count++;
}
else
{
temp = (node*)malloc(sizeof(node));
memset(temp,0,sizeof(node));
temp->value = value;
temp->count++;
temp->pnext = listhead;
listhead = temp;
*pplisthead = listhead;
}
}
else
{
listhead = (node*)malloc(sizeof(node));
memset(listhead,0,sizeof(node));
listhead->value = value;
listhead->count++;
listhead->pnext = NULL;
*pplisthead = listhead;
}
}
//对链表进行冒泡排序
node *bubblesortlist(node* listhead)
{
node *pNode1 = listhead;
node *pNode2 = listhead;
if(listhead == NULL)
{
return listhead;
}
for(;pNode1->pnext!=NULL;pNode1=pNode1->pnext)
{//外层循环只是起到计数作用,对于冒泡排序,每次得到一个确定的位序,进行n次排序得到完整序列
for(pNode2=listhead;pNode2->pnext!=NULL;pNode2=pNode2->pnext)
{
if(pNode2->count < pNode2->pnext->count)
{
int tempvalue = pNode2->value;
int tempcount = pNode2->count;
pNode2->value = pNode2->pnext->value;
pNode2->count = pNode2->pnext->count;
pNode2->pnext->value = tempvalue;
pNode2->pnext->count = tempcount;
}
}
}
return listhead;
}
int* topKFrequent(int* nums, int numsSize, int k, int* returnSize) {
node *hashhead = NULL;
for(int i =0 ;i < numsSize;i++)
{
CreatehashList(&hashhead,nums[i]);//建立hash链
}
//对链表排序
hashhead = bubblesortlist(hashhead);
int *retarray = (int*)malloc(sizeof(int)*k);
*returnSize = 0;
int j = 0;
while((hashhead!=NULL)&&(j < k))
{
retarray[(*returnSize)++] = hashhead->value;
hashhead = hashhead->pnext;
j++;
}
return retarray;
}
//其实我使用冒泡排序,时间复杂度已经是O(n^2)了,
//不符合题目的O(nlogn),我可以使用堆排序来进行排序