215. Kth Largest Element in an Array
Find thekth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given[3,2,1,5,6,4]
and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
Solution:
直接调用 python heapq, 保持size k, 然后loop thru nums array,最后直接 heap pop 就是结果。
因为,python 的heapq 是 min heap
ref:https://docs.python.org/2/library/heapq.html
import heapq
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
# heap
h = nums[:k]
heapq.heapify(h)
n = len(nums)
for i in range(k, n):
heapq.heappushpop(h, nums[i])
return heapq.heappop(h)