This approach uses a hash map to count the frequency of each element. We then use a min-heap to keep track of the top k elements.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) for storing frequencies.
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5#define MAX 10000
6
7typedef struct {
8 int value;
9 int count;
10} Freq;
11
12int compare(const void *a, const void *b) {
13 return ((Freq *)b)->count - ((Freq *)a)->count;
14}
15
16int* topKFrequent(int* nums, int numsSize, int k, int* returnSize) {
17 int freqMap[2 * MAX + 1] = {0};
18 Freq freqArray[numsSize];
19 int uniqueCount = 0;
20
21 for(int i = 0; i < numsSize; i++) {
22 freqMap[nums[i] + MAX]++;
23 }
24
25 for(int i = 0; i < 2 * MAX + 1; i++) {
26 if(freqMap[i]) {
27 freqArray[uniqueCount].value = i - MAX;
28 freqArray[uniqueCount].count = freqMap[i];
29 uniqueCount++;
30 }
31 }
32
33 qsort(freqArray, uniqueCount, sizeof(Freq), compare);
34
35 *returnSize = k;
36 int *result = (int*)malloc(sizeof(int) * k);
37 for(int i = 0; i < k; i++) {
38 result[i] = freqArray[i].value;
39 }
40 return result;
41}
42
43int main() {
44 int nums[] = {1, 1, 1, 2, 2, 3};
45 int k = 2;
46 int returnSize;
47 int* result = topKFrequent(nums, 6, k, &returnSize);
48 for(int i = 0; i < returnSize; i++) {
49 printf("%d ", result[i]);
50 }
51 free(result);
52 return 0;
53}
54
We use a frequency map to track occurrences of each number. Then, we create a struct array for frequencies, sort it, and return the top k elements.
This approach involves using bucket sort where we create buckets for frequency counts and then extract the top k frequent elements.
Time Complexity: O(n + k).
Space Complexity: O(n).
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5public class Solution {
6 public int[] TopKFrequent(int[] nums, int k) {
7 var freqMap = new Dictionary<int, int>();
8 foreach (var num in nums) {
9 if (!freqMap.ContainsKey(num))
10 freqMap[num] = 0;
11 freqMap[num]++;
12 }
13
14 List<int>[] buckets = new List<int>[nums.Length + 1];
15 foreach (var pair in freqMap) {
16 int freq = pair.Value;
17 if (buckets[freq] == null)
18 buckets[freq] = new List<int>();
19 buckets[freq].Add(pair.Key);
20 }
21
22 List<int> res = new List<int>();
23 for (int i = buckets.Length - 1; i >= 0 && res.Count < k; --i) {
24 if (buckets[i] != null)
25 res.AddRange(buckets[i].ToArray());
26 }
27
28 return res.Take(k).ToArray();
29 }
30
31 public static void Main(string[] args) {
32 int[] nums = new int[] {1, 1, 1, 2, 2, 3};
33 int k = 2;
34 Solution sol = new Solution();
35 int[] result = sol.TopKFrequent(nums, k);
36 Console.WriteLine(string.Join(", ", result));
37 }
38}
39
In this C# implementation, frequency of elements is handled with lists representing buckets, aiding the direct extraction of frequent elements.