1.双端队列法

  1. /*
  2. * @lc app=leetcode.cn id=239 lang=javascript
  3. *
  4. * [239] 滑动窗口最大值
  5. */
  6. // @lc code=start
  7. /**
  8. * @param {number[]} nums
  9. * @param {number} k
  10. * @return {number[]}
  11. */
  12. var maxSlidingWindow = function (nums, k) {
  13. if (nums.length === 0 || !k) return []
  14. let windows = []
  15. let res = []
  16. for (let i = 0; i < nums.length; i++) {
  17. if (windows[0] !== undefined && windows[0] <= i - k) windows.shift()
  18. while (nums[windows[windows.length - 1]] <= nums[i]) windows.pop()
  19. windows.push(i)
  20. if (i >= k - 1) res.push(nums[windows[0]])
  21. }
  22. return res
  23. }
  24. // @lc code=end