Press "Enter" to skip to content

Posts tagged as “deque”

花花酱 LeetCode 239. Sliding Window Maximum

题目大意:给你一个数组,让你输出移动窗口的最大值。

Problem:

https://leetcode.com/problems/sliding-window-maximum/

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.

For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

Therefore, return the max sliding window as [3,3,5,5,6,7].

Note: 
You may assume k is always valid, ie: 1 ≤ k ≤ input array’s size for non-empty array.

Follow up:
Could you solve it in linear time?

 

Idea:

 

Solution 1: Brute Force

Time complexity: O((n – k + 1) * k)

Space complexity: O(1)

C++

Java

Python

Solution 2: BST

Time complexity: O((n – k + 1) * logk)

Space complexity: O(k)

C++

Solution 3: Monotonic Queue

Time complexity: O(n)

Space complexity: O(k)

C++

C++ V2

C++ V3

Java

Python3

Python3 V2