- Kth Largest Element in a Stream
class KthLargest(object):
def __init__(self, k, nums):
"""
:type k: int
:type nums: List[int]
"""
self.pool=nums
self.size=len(self.pool)
self.k=k
heapq.heapify(self.pool)
while self.size>k:
heapq.heappop(self.pool)
self.size-=1
def add(self, val):
"""
:type val: int
:rtype: int
"""
if self.size<self.k:
heapq.heappush(self.pool,val)
self.size+=1
elif val>self.pool[0]:
heapq.heapreplace(self.pool,val)
return self.pool[0]
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
注释:
Python内置的heapq模块
heapq.heappush(heap,item):将item,推入heap
heapq.heappop(heap):将heap的最小值pop出heap,heap为空时报IndexError错误
heapq.heappushpop(heap,item):pop出heap中最小的元素,推入item
heapq.heapify(x):将list X转换为heap
heapq.heapreplace(heap,item):pop出最小值,推入item,heap的size不变
heapq.merge(*iterable):将多个可迭代合并,并且排好序,返回一个iterator
heapq.nlargest(n,iterable,key):返回item中大到小顺序的前N个元素,key默认为空,可以用来指定规则如:function等来处理特定的排序,如果没有指定key,那么就按照第一个字段来排序
自己实现堆排序
https://www.jianshu.com/p/d174f1862601
leetcode239
class Solution(object):
def maxSlidingWindow(self, nums, k):
opt = []
q = collections.deque()
for i in xrange(len(nums)):
n = nums[i]
#move the window
if q and q[0]<=i-k: q.popleft()
#pop the right if the element in queue is not greater than the in-coming one
#by doing this, we can always keep the max in the current window at left most
while q and nums[q[-1]]<=n: q.pop()
q.append(i)
#add the max to the output array after the first kth element
if 1+i>=k: opt.append(nums[q[0]])
return opt