?題目描述
給你一個(gè)整數(shù)數(shù)組?nums
,有一個(gè)大小為?k
?的滑動(dòng)窗口從數(shù)組的最左側(cè)移動(dòng)到數(shù)組的最右側(cè)。你只可以看到在滑動(dòng)窗口內(nèi)的?k
?個(gè)數(shù)字?;瑒?dòng)窗口每次只向右移動(dòng)一位。文章來源:http://www.zghlxwxcb.cn/news/detail-667612.html
返回?滑動(dòng)窗口中的最大值?。文章來源地址http://www.zghlxwxcb.cn/news/detail-667612.html
示例一
輸入:nums = [1,3,-1,-3,5,3,6,7], k = 3
輸出:[3,3,5,5,6,7]
解釋:
滑動(dòng)窗口的位置 最大值
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
示例二
輸入:nums = [1], k = 1
輸出:[1]
代碼實(shí)現(xiàn)
# coding:utf-8
# 滑動(dòng)窗口最大值
# https://leetcode.cn/problems/sliding-window-maximum/
class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
ans = []
que = []
for i in range(len(nums)):
while que and ((i - k + 1) > k):
del que[0]
while que and (nums[que[-1]] < nums[i]):
que.pop()
que.append(i)
if k and (i >= k - 1):
ans.append(nums[que[0]])
return ans
if __name__ == '__main__':
s = list(map(int, (input("input arry:").split(','))))
k = int(input("input K:").split(' ')[0])
solution = Solution()
print(solution.maxSlidingWindow(s, k))
到了這里,關(guān)于華為OD-滑動(dòng)窗口最大值的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!