題目 |
題目傳送門:傳送門(點擊此處)
題解 |
思路
這道題目是有難度的,如果使用先排序的方法,就有一點墨跡了,所以我們這道題目藉助堆的數據結構,實現最大堆就可以了
代碼
class Solution {
public int findKthLargest(int[] nums, int k) {
// init heap 'the smallest element first'
PriorityQueue<Integer> heap = new PriorityQueue<Integer>((n1, n2) -> n1 - n2);
// keep k largest elements in the heap
for (int n : nums) {
heap.add(n);
if (heap.size() > k)
heap.poll();
}
// output
return heap.poll();
}
}