-
题目描述:给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按任意顺序 返回答案。
-
示例
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]输入: nums = [1], k = 1
输出: [1] -
提示
-
前 K 个高频元素
-
解题思路:
(1)将每一个数组nums元素放进哈希表中,以元素值作为键,并为每个元素出现次数计数;
(2)给节点排序,uthash库中包含了哈希表的查询、插入、删除和排序等功能,包含的 HASH_SORT 函数可以根据key或者count值对哈希表的内容进行排序。本题应当依据count值进行从大到小排序,最后依次输出前k个哈希表的key值。 -
代码:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
struct hash_table {
int ikey; // 键值nums[i]
int count; // 计数
UT_hash_handle hh;
};
struct hash_table *h;
struct hash_table* find(int ikey)
{
struct hash_table *s = NULL;
HASH_FIND_INT(h,&ikey,s);
return s;
}
void insert(int ikey)
{
struct hash_table *s = find(ikey);
if(s==NULL)
{
s = (struct hash_table*)malloc(sizeof(struct hash_table));
s->ikey = ikey;
s->count = 1;
HASH_ADD_INT(h, ikey, s);
}
else
{
s->count++;
}
}
// 类似于qsort函数里的cmp函数,确定排序是从大到小还是从小到大
int count_sort(struct hash_table *a, struct hash_table *b) {
return (b->count - a->count);//依据count值从大到小排序
}
int* topKFrequent(int* nums, int numsSize, int k, int* returnSize){
*returnSize = k;
h = NULL;
for(int i=0;i<numsSize;i++)
{
insert(nums[i]);
}
int *ret = (int*)malloc(sizeof(int)*k);
// 对哈希表依据count值进行排序
HASH_SORT(h, count_sort);
struct hash_table *s;
int index = 0;
for(s = h;index < k; s = s->hh.next)
{
ret[index++] = s->ikey;
}
return ret;
}
- 时间复杂度?空间复杂度?