[LeetCode]215. Kth Largest Element in an Array (Medium) Python-2023.08.14
Posted on 2023-08-14 17:02 Uriel 閱讀(46) 評論(0) 編輯 收藏 引用 所屬分類: 數據結構 、閑來無事重切Leet Code求一列數第k大的數,heap應用
1 #215
2 #Runtime: 822 ms (Beats 46.88%)
3 #Memory: 23.3 MB (Beats 81.50%)
4
5 class Solution(object):
6 def findKthLargest(self, nums, k):
7 """
8 :type nums: List[int]
9 :type k: int
10 :rtype: int
11 """
12 hp = []
13 for n in nums:
14 heapq.heappush(hp, n)
15 if len(hp) > k:
16 heapq.heappop(hp)
17 return hp[0]
2 #Runtime: 822 ms (Beats 46.88%)
3 #Memory: 23.3 MB (Beats 81.50%)
4
5 class Solution(object):
6 def findKthLargest(self, nums, k):
7 """
8 :type nums: List[int]
9 :type k: int
10 :rtype: int
11 """
12 hp = []
13 for n in nums:
14 heapq.heappush(hp, n)
15 if len(hp) > k:
16 heapq.heappop(hp)
17 return hp[0]