[leetcode]Kth Largest Element in an Array

注意第K大,要用小顶堆。因为get取走的都是小的,留下的k个都是最大的。

from queue import PriorityQueue

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        pq = PriorityQueue()
        for num in nums:
            pq.put(num) # smaller first
            if pq.qsize() > k:
                pq.get()
                
        result = pq.get()
        return result

  

你可能感兴趣的:([leetcode]Kth Largest Element in an Array)