I am working on an interview question where I need to return the k most frequent elements given a non-empty array of integers..
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Here is my code:
public static void main(String[] args) {
System.out.println(topKFrequent(new int[] {1, 1, 1, 2, 2, 3, 3}, 1));
}
private static List<Integer> topKFrequent(int[] nums, int k) {
// freq map
Map<Integer, Integer> freq = new HashMap<Integer, Integer>();
for (int n : nums) {
freq.put(n, freq.getOrDefault(n, 0) + 1);
}
// bucket sort on freq
List<Integer>[] bucket = new LinkedList[nums.length + 1];
for (int i = 0; i < bucket.length; i++)
bucket[i] = new LinkedList<>();
for (int key : freq.keySet()) {
bucket[freq.get(key)].add(key);
}
// gather result
List<Integer> res = new ArrayList<>();
for (int i = bucket.length - 1; i >= 0; i--) {
res.addAll(bucket[i]);
if (res.size() >= k)
break;
}
return res;
}
I wanted to check whether there is any improvement/optimization can be made in this code? I am confuse in the case when more than one numbers with the same frequency exists. What should we do in that case?