您的位置:首页 > 产品设计 > UI/UE

leetcode 347. Top K Frequent Elements

2017-08-23 10:47 357 查看
原题:

Given a non-empty array of integers, return the k most frequent elements.

For example,

Given 
[1,1,1,2,2,3]
 and k = 2, return 
[1,2]
.

Note: 

You may assume k is always valid, 1 ? k ? number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

代码如下:

/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* topKFrequent(int* nums, int numsSize, int k, int* returnSize) {
struct node
{
int value;
int times;
};
struct node* head;
head=(struct node*)malloc(sizeof(struct node)*numsSize);
int n=0;
for(int m=0;m<numsSize;m++)
{
int flag=0;
if(n==0)
flag=1;
else
{
for(int k=0;k<n;k++)
{
if((head+k)->value==*(nums+m))
{
((head+k)->times)+=1;
flag=0;
break;
}
flag=1;
}
}
if(flag==1)
{
(head+n)->value=*(nums+m);
(head+n)->times=0;
n++;
}
}
for(int m=0;m<n;m++)
{
printf("P%d,%d",(head+m)->value,(head+m)->times);
}
int cmpst(const void *a,const void* b)
{
return (*(struct node*)b).times-(*(struct node*)a).times;
}
qsort(head,numsSize,sizeof(head[0]),cmpst);
int* result;
result=(int*)malloc(sizeof(int)*k);
for(int m=0;m<n;m++)
{
printf("L%d,%d",(head+m)->value,(head+m)->times);
}
for(;*returnSize<k;(*returnSize)++)
{
*(result+*returnSize)=(head+*returnSize)->value;
}
return result;
}就是依次统计出现次数,进行一下排列而已。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: