347. Top K Frequent Elements
by Botao Xiao
Question
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Thinking:
- Method 1:
class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
List<Integer> res = new ArrayList<>();
for(int num : nums){
map.put(num, map.containsKey(num)?map.get(num) + 1: 1);
}
Set<Map.Entry<Integer, Integer>> set = map.entrySet();
PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>(new Comparator<Map.Entry<Integer, Integer>>(){
@Override
public int compare(Map.Entry<Integer, Integer> n1, Map.Entry<Integer, Integer> n2){
return n2.getValue() - n1.getValue();
}
});
for(Map.Entry<Integer, Integer> entry: set){
pq.offer(entry);
}
for(int i = 0; i < k; i++){
res.add(pq.poll().getKey());
}
return res;
}
}
Subscribe via RSS