import java.util.PriorityQueue; public class Solution { public static void main(String[] args) { int[] nums1 = {3,2,1,5,6,4}; System.out.println(findKthLargest(nums1, 2)); //5 int[] nums2 = {3,2,3,1,2,4,5,5,6}; System.out.println(findKthLargest(nums2, 4)); //4 } public static int findKthLargest(int[] nums, int k) { // init heap 'the smallest element first' 小顶堆 PriorityQueue<Integer> heap = new PriorityQueue<Integer>(); for (int n: nums) { heap.add(n); // 添加 if (heap.size() > k){ // keep k largest elements in the heap heap.poll(); // 从小顶堆的堆顶删除 } } return heap.poll(); } }