面试题65:滑动窗口的最大值

2019-05-05  本文已影响0人  gpfworld

题目

https://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788?tpId=13&tqId=11217&tPage=4&rp=4&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

Code

# -*- coding:utf-8 -*-
from collections import deque
class Solution:
    def maxInWindows(self, num, size):
        # write code here
        maxinNum = []
        if len(num) >= size and size >= 1:
            index = deque()
            for i in range(size):
                while index and num[i] > num[index[-1]]:
                    index.pop()
                index.append(i)
            for i in range(size,len(num)):
                maxinNum.append(num[index[0]])
                while index and num[i] > num[index[-1]]:
                    index.pop()
                if len(index)!=0  and index[0] <= (i -size):
                    index.popleft()
                index.append(i)
            maxinNum.append(num[index[0]])
        return maxinNum

注意:
index 对象判空的用法
while index and num[i] > num[index[-1]]:

上一篇下一篇

猜你喜欢

热点阅读