Leetcode 215. Kth Largest Element in an Array
题目
解法1:brutal force
每次取出一个最大的,直到取到第K个为止。时间复杂度n*n
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
for i in range(k-1):
curr_max = max(nums)
nums.remove(curr_max)
return max(nums)
解法2:heap,最小堆
构造一个大小为K的最小堆,然后一个个把元素加入最小堆,但一直保持堆的大小是K。到最后堆顶元素就是我们要寻找的答案
class Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
min_heap = []
for i in range