1. 程式人生 > >215. Kth Largest Element in an Array

215. Kth Largest Element in an Array

ret span self div arr [] 如果 說明 ace

用heap解,

方法1. 維護一個 size = k 的最小堆。當前元如果大於堆頂的元素,那麽說明堆頂的元素肯定小於kth largest element。所以replace他。

 1 class Solution(object):
 2     def findKthLargest(self, nums, k):
 3         """
 4         :type nums: List[int]
 5         :type k: int
 6         :rtype: int
 7         """
 8         heap = []
 9         res = 0
10 11 for i in range(len(nums)): 12 if i < k: 13 heapq.heappush(heap, nums[i]) 14 else: 15 if heap[0] < nums[i]: 16 heapq.heapreplace(heap, nums[i]) 17 18 19 return heap[0]

或者維護一個-nums的最小堆,從heap pop出第k個元素。那麽這個數就是 -nums的第k小元素,也就是nums的第k大元素。

class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        heap = []
        res = 0
        
        for i in range(len(nums)):
            heapq.heappush(heap, -nums[i])
        
        for
j in range(k): res = -heapq.heappop(heap) return res

215. Kth Largest Element in an Array