思路

题目地址:https://leetcode-cn.com/problems/kth-largest-element-in-an-array/

有两种解决思路,一种是最小堆,一种是快排

最小堆

  1. 它是一颗完全二叉树,它可以是空
  2. 树中结点的值总是不大于或者不小于其孩子结点的值
  3. 每一个结点的子树也是一个堆

当父结点的键值总是大于或等于任何一个子结点的键值时为最大堆,当父结点的键值总是小于或等于任何一子节点的键值时为最小堆

PriorityQueue默认为最小堆,改变排序规则为最大堆

public class Demo {

public static void main(String[] args) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
minHeap.add(10);
minHeap.add(5);
minHeap.add(15);
minHeap.add(2);
while (!minHeap.isEmpty()) {
// 2 5 10 15
System.out.println(minHeap.poll());
}
System.out.println("---");
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((n1, n2) -> n2 - n1);
maxHeap.add(10);
maxHeap.add(5);
maxHeap.add(15);
maxHeap.add(2);
while (!maxHeap.isEmpty()) {
// 15 10 5 2
System.out.println(maxHeap.poll());
}
}
}

快排

代码

最小堆

public class Solution {

public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>();
for (int n : nums) {
heap.add(n);
if (heap.size() > k) {
heap.poll();
}
}
return heap.poll();
}

}

参考博客

[1]Java面试总结

[2]https://www.jianshu.com/p/62b651797ad8