堆
public static int majorityElement3(int[] nums) {
int len = (nums.length + 1) / 2;
//定义大根堆,堆顶最大,求top-k小问题
PriorityQueue<Integer> queue = new PriorityQueue<>(len, Comparator.comparingLong(item -> -item));
for (int num : nums) {
queue.offer(num);
if (queue.size() > len) {
queue.poll();
}
}
return queue.poll();
}
//定义小根堆,堆顶最小,求top-k大问题 默认小根堆--求最大
PriorityQueue<Integer> queue = new PriorityQueue<>(len, Comparator.comparingLong(item -> item));
//定义大根堆,堆顶最大,求top-k小问题
PriorityQueue<Integer> queue = new PriorityQueue<>(len, Comparator.comparingLong(item -> -item));