Posted on 2023-05-23 19:37
Uriel 閱讀(52)
評論(0) 編輯 收藏 引用 所屬分類:
數據結構 、
閑來無事重切Leet Code
求一列數的第K大,優先隊列打卡題
1 #703
2 #Runtime: 95 ms (Beats 80.5%)
3 #Memory: 17.9 MB (Beats 17.87%)
4
5 class KthLargest(object):
6
7 def __init__(self, k, nums):
8 """
9 :type k: int
10 :type nums: List[int]
11 """
12 self.nums = nums
13 self.K = k
14 heapify(self.nums)
15 while len(self.nums) > self.K:
16 heappop(self.nums)
17
18 def add(self, val):
19 """
20 :type val: int
21 :rtype: int
22 """
23 if len(self.nums) < self.K:
24 heappush(self.nums, val)
25 elif val > self.nums[0]:
26 heapreplace(self.nums, val)
27 return self.nums[0]
28
29
30
31 # Your KthLargest object will be instantiated and called as such:
32 # obj = KthLargest(k, nums)
33 # param_1 = obj.add(val)