【LeetCode】 215. 數組中的第K個最大元素 大頂堆

題目

題目傳送門:傳送門(點擊此處)
在這裏插入圖片描述

題解

思路

這道題目是有難度的,如果使用先排序的方法,就有一點墨跡了,所以我們這道題目藉助堆的數據結構,實現最大堆就可以了

代碼

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();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章