鱼C论坛

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

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

[复制链接]
发表于 2020-7-30 11:44:19 | 显示全部楼层 |阅读模式

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

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

x
本帖最后由 Seawolf 于 2020-7-30 11:46 编辑
  1. Given an array 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.

  2. Follow up:
  3. Could you solve it in linear time?

  4. Example:

  5. Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
  6. Output: [3,3,5,5,6,7]
  7. Explanation:

  8. Window position                Max
  9. ---------------               -----
  10. [1  3  -1] -3  5  3  6  7       3
  11. 1 [3  -1  -3] 5  3  6  7       3
  12. 1  3 [-1  -3  5] 3  6  7       5
  13. 1  3  -1 [-3  5  3] 6  7       5
  14. 1  3  -1  -3 [5  3  6] 7       6
  15. 1  3  -1  -3  5 [3  6  7]      7


  16. Constraints:

  17. 1 <= nums.length <= 10^5
  18. -10^4 <= nums[i] <= 10^4
  19. 1 <= k <= nums.length
复制代码

  1. 给定一个数组 nums,有一个大小为k;的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k个数字。滑动窗口每次只向右移动一位。

  2. 返回滑动窗口中的最大值。


  3. 进阶:

  4. 你能在线性时间复杂度内解决此题吗?


  5. 示例:

  6. 输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
  7. 输出: [3,3,5,5,6,7]
  8. 解释:

  9.   滑动窗口的位置                最大值
  10. ---------------               -----
  11. [1  3  -1] -3  5  3  6  7       3
  12. 1 [3  -1  -3] 5  3  6  7       3
  13. 1  3 [-1  -3  5] 3  6  7       5
  14. 1  3  -1 [-3  5  3] 6  7       5
  15. 1  3  -1  -3 [5  3  6] 7       6
  16. 1  3  -1  -3  5 [3  6  7]      7

  17. 提示:

  18. 1 <= nums.length <= 10^5
  19. -10^4<= nums[i]<= 10^4
  20. 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-4-17 02:23

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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