鱼C论坛

 找回密码
 立即注册
查看: 2578|回复: 0

[学习笔记] Leetcode 239. Sliding Window Maximum

[复制链接]
发表于 2020-9-23 03:43:03 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

Return the max sliding window.



Example 1:

Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position                Max
---------------               -----
[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
Example 2:

Input: nums = [1], k = 1
Output: [1]
Example 3:

Input: nums = [1,-1], k = 1
Output: [1,-1]
Example 4:

Input: nums = [9,11], k = 2
Output: [11]
Example 5:

Input: nums = [4,-2], k = 2
Output: [4]


Constraints:

1 <= nums.length <= 105
-104 <= nums <= 104
1 <= k <= nums.length

  1. from collections import deque
  2. class Solution:
  3.     def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
  4.         queue = deque()
  5.         res = []
  6.         if len(nums) == 0:
  7.             return res
  8.         for i in range(k - 1):
  9.             self.indeque(queue, nums[i])
  10.         for i in range(k - 1, len(nums)):
  11.             self.indeque(queue, nums[i])
  12.             res.append(queue[0])
  13.             self.outdeque(queue, nums[i - k + 1])
  14.         return res
  15.    
  16.     def indeque(self, queue: List[int], num: int) -> None:
  17.         while len(queue) != 0 and queue[-1] < num:
  18.             queue.pop()
  19.         queue.append(num)
  20.    
  21.     def outdeque(self, queue: List[int], num: int) -> None:
  22.         if queue[0] == num:
  23.             queue.popleft()
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-5 13:21

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表