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.
1import java.util.*;
2
3class Solution {
4 public int[] topKFrequent(int[] nums, int k) {
5 Map<Integer, Integer> freqMap = new HashMap<>();
6 for (int num : nums) {
7 freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
8 }
9
10 PriorityQueue<Integer> minHeap = new PriorityQueue<>((a, b) -> freqMap.get(a) - freqMap.get(b));
11 for (int num : freqMap.keySet()) {
12 minHeap.add(num);
13 if (minHeap.size() > k) {
14 minHeap.poll();
15 }
16 }
17
18 int[] result = new int[k];
19 for (int i = k - 1; i >= 0; i--) {
20 result[i] = minHeap.poll();
21 }
22 return result;
23 }
24
25 public static void main(String[] args) {
26 Solution sol = new Solution();
27 int[] nums = {1,1,1,2,2,3};
28 int k = 2;
29 int[] result = sol.topKFrequent(nums, k);
30 System.out.println(Arrays.toString(result));
31 }
32}
33
HashMap is used to record the frequency of each element, and a min heap of size k keeps track of the top k elements based on frequency.
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.