347. Top K Frequent Elements (Medium) Yelp PocketGems
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given[1,1,1,2,2,3]
and k = 2, return[1,2]
.
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
Solution 1: Bucket Sort O(n); O(n)
use an array to save numbers into different bucket whose index is the frequency
public List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for (int n : nums) {
map.put(n, map.getOrDefault(n, 0) + 1);
}
// corner case: if there is only one number in nums, we need the bucket has index 1.
List<Integer>[] bucket = new List[nums.length + 1]; //很少见的写法,要记住
for (int key : map.keySet()) {
int freq = map.get(key);
if (bucket[freq] == null) {
bucket[freq] = new ArrayList<>();
}
bucket[freq].add(key);
}
List<Integer> res = new ArrayList<>();
for (int i = bucket.length - 1; i >= 0 && res.size() < k; i--) {
if (bucket[i] != null) {
res.addAll(bucket[i]);
}
}
return res;
}
Solution 2: maxHeap O(n log n); O(n)
Use a HashMap to store each number and its frequency.
Then use a max heap to store each entry(max heap's key) of the HashMap and the comparator of max heap is sorting the entry according to entry's value, so we can always poll a number with largest frequency.
Poll entries from max heap and add its key, which is the number, to the result until the result's size is k.
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
return res;
}
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
PriorityQueue<Map.Entry<Integer, Integer>> maxHeap = new
PriorityQueue<>((a, b) -> b.getValue() - a.getValue());
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
maxHeap.offer(entry);
}
while (res.size() < k) { //important
res.add(maxHeap.poll().getKey());
}
return res;
}
Solutoin 3: TreeMap (n log n); O(n)
// use treeMap. Use freqncy as the key so we can get all freqencies in order
public List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for(int n: nums){
map.put(n, map.getOrDefault(n,0)+1);
}
TreeMap<Integer, List<Integer>> freqMap = new TreeMap<>();
for(int num : map.keySet()){
int freq = map.get(num);
if(!freqMap.containsKey(freq)){
freqMap.put(freq, new LinkedList<>());
}
freqMap.get(freq).add(num);
}
List<Integer> res = new ArrayList<>();
while(res.size()<k){
Map.Entry<Integer, List<Integer>> entry = freqMap.pollLastEntry();
res.addAll(entry.getValue());
}
return res;
}