leetcode Kth Largest Element in a Stream——要熟悉heapq使用
703. Kth Largest Element in a Stream
Easy
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Your KthLargest
class will have a constructor which accepts an integer k
and an integer array nums
, which contains initial elements from the stream. For each call to the method KthLargest.add
, return the element representing the kth largest element in the stream.
Example:
int k = 3; int[] arr = [4,5,8,2]; KthLargest kthLargest = new KthLargest(3, arr); kthLargest.add(3); // returns 4 kthLargest.add(5); // returns 5 kthLargest.add(10); // returns 5 kthLargest.add(9); // returns 8 kthLargest.add(4); // returns 8
Note:
You may assume that nums
' length ≥ k-1
and k
≥ 1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | """ 1 import heapq 2 def heapsort(iterable): 3 h = [] 4 for i in iterable: 5 heapq.heappush(h, i) 6 return [heapq.heappop(h) for i in range(len(h))] 7 8 # method 1: sort to list 9 s = [3, 5, 1, 2, 4, 6, 0, 1] 10 print(heapsort(s)) 11 ''' 12 [0, 1, 1, 2, 3, 4, 5, 6] 13 ''' """ import heapq class KthLargest( object ): def __init__( self , k, nums): """ :type k: int :type nums: List[int] """ self .arr = [] self .k = k for i in nums: if len ( self .arr) < self .k: heapq.heappush( self .arr, i) else : if i > self .arr[ 0 ]: #if heapq.nsmallest(1, self.arr)[0] < i: heapq.heapreplace( self .arr, i) #heapq.heappop(self.arr) #heapq.heappush(self.arr, i) def add( self , val): """ :type val: int :rtype: int """ if len ( self .arr) < self .k: heapq.heappush( self .arr, val) else : if val > self .arr[ 0 ]: #if heapq.nsmallest(1, self.arr)[0] < val: heapq.heapreplace( self .arr, val) #heapq.heappop(self.arr) #heapq.heappush(self.arr, val) assert len ( self .arr) = = self .k return self .arr[ 0 ] #return heapq.nsmallest(1, self.arr)[0] # Your KthLargest object will be instantiated and called as such: # obj = KthLargest(k, nums) # param_1 = obj.add(val) |
注意:如果使用heapq.nsmallest(1, self.arr)[0]来返回heap的最小值会有超时问题。
标签:
算法
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2016-12-09 英语中逗号作用
2016-12-09 splunk LB和scale(根本在于分布式扩展index,search)
2016-12-09 Splunk Enterprise architecture——转发器本质上是日志收集client附加负载均衡,indexer是分布式索引,外加一个集中式管理协调的中心节点
2016-12-09 c中gets函数使用可能导致缓冲区溢出
2016-12-09 日志易——中国版的splunk