Posted on 2023-05-23 19:37
Uriel 阅读(36)
评论(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)