347. 前 K 个高频元素

给定一个非空的整数数组,返回其中出现频率前 k* 高的元素。 示例 1:**

  1. 输入: nums = [1,1,1,2,2,3], k = 2
  2. 输出: [1,2]

示例 2:

  1. 输入: nums = [1], k = 1
  2. 输出: [1]

提示:

  • 你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
  • 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
  • 题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的。
  • 你可以按任意顺序返回答案。

代码实现

  1. /**
  2. * Note: The returned array must be malloced, assume caller calls free().
  3. */
  4. #include<stdlib.h>
  5. #include<stdio.h>
  6. #define N 10000
  7. #define OFFSITE 5000
  8. struct Node{
  9. int data;
  10. int num;
  11. };
  12. struct Node countFre[N];
  13. int cmp ( const void *a , void *b){
  14. struct Node *na = ( struct Node *)a;
  15. struct Node *nb = ( struct Node *)b;
  16. return nb->num - na->num;
  17. }
  18. int* topKFrequent(int* nums, int numsSize, int k, int* returnSize){
  19. //初始化countFre
  20. memset(countFre,0,sizeof(struct Node)*N);
  21. int index;
  22. for(int i=0;i<numsSize;i++){
  23. index = (nums[i]+ OFFSITE)%N;
  24. countFre[index].num++;
  25. countFre[index].data = nums[i];
  26. }
  27. //将countFre做紧凑
  28. int j=0;
  29. for(int i=0;i<N;i++){
  30. if(countFre[i].num != 0){
  31. countFre[j++] = countFre[i];
  32. }
  33. }
  34. qsort(countFre,j,sizeof(countFre[0]),&cmp);
  35. int* res = (int*)malloc(sizeof(int)*k);
  36. for(int i=0;i<k;i++){
  37. res[i] = countFre[i].data;
  38. }
  39. *returnSize = k;
  40. return res;
  41. }