描述
给定一个非空的整数数组,返回其中出现频率前 高的元素。
样例
样例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
样例 2:
输入: nums = [1], k = 1
输出: [1]
public class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer, Integer> occurrences = new HashMap<Integer, Integer>();
for (int num : nums) {
occurrences.put(num, occurrences.getOrDefault(num, 0) + 1);
}
PriorityQueue<int[]> queue = new PriorityQueue<int[]>(new Comparator<int[]>() {
public int compare(int[] m, int[] n) {
return m[1] - n[1];
}
});
for (Map.Entry<Integer, Integer> entry : occurrences.entrySet()) {
int num = entry.getKey(), count = entry.getValue();
if (queue.size() == k) {
if (queue.peek()[1] < count) {
queue.poll();
queue.offer(new int[]{num, count});
}
} else {
queue.offer(new int[]{num, count});
}
}
List<Integer> ret = new ArrayList<>();
for (int i = 0; i < k; ++i) {
ret.add(queue.poll()[0]);
}
return ret;
}
}