python滑动窗口

  1. 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
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值