215. Kth Largest Element in an Array

Medium

這題很明顯,并非那么簡(jiǎn)單. 邏輯很直白的,多半是想考你最優(yōu)解法,時(shí)間空間復(fù)雜度最低。

我用的最intuitive的解法,建立一個(gè)從大到小的priorityQueue, 把所有數(shù)組元素丟進(jìn)去,然后一個(gè)一個(gè)取取到第k個(gè).
O(N lg K) running time + O(K) memory
為什么這里時(shí)間復(fù)雜度是O(NlgK)而不是O(N)呢,因?yàn)閜riorityQueue本質(zhì)上是Binary heap, which is quite like a complete binary tree. 它的insert()和delete()都是O(lgK),而我們遍歷了array里的N個(gè)元素來進(jìn)行insert or delete, 所以是O(Nlg

class Solution {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> pq = new PriorityQueue<>(nums.length, new Comparator<Integer>(){
            public int compare(Integer a, Integer b){
                return b - a;
            }
        });
        for (Integer i : nums){
            pq.offer(i);
        }
        int topK = 0;
        while (k > 0){
            topK = pq.poll();
            k--;
        }
        return topK;
    }
}

然而這肯定不是面試官想要的解法,為了這個(gè)寫這個(gè)QuickSelect解法我花了感覺大半天時(shí)間吧。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容