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.
Example:
Input: nums =[1,3,-1,-3,5,3,6,7]
, and 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
Note:
You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.
Follow up:
Could you solve it in linear time?
给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口 k 内的数字。滑动窗口每次只向右移动一位。
返回滑动窗口最大值。
示例:
输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
--------------- -----
[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
注意:
你可以假设 k 总是有效的,1 ≤ k ≤ 输入数组的大小,且输入数组不为空。
进阶:
你能在线性时间复杂度内解决此题吗?
解题思路:
选一段区间内的最大值,一开始我就想用优先级队列(堆)来做,但是问题在于如果nums[i - k + 1]的数是这段区间内的最大值而区间右移时如何处理 ; 因为优先级队列是不能指定删除某个元素的,也不能查找某个元素在堆中的位置;所以既能将元素排序又能将查找元素对应的位置的数据结构可选的有set/multiset , map/multimap, 这里选multiset ;
解法一:
遍历nums中的元素,将元素放置multiset中,当i >= k - 1时,将multiset中的最后一个元素加入res中,因为multiset是默认升序排列的。然后查找nums[i - k + 1]元素在multiset中的位置,并删除。不能直接使用erase(nums[i - k + 1]),因为会将所有等于nums[i - k + 1]的元素都删掉。
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k)
{
int len = nums.size() ;
multiset<int> ms ;
vector<int> ans ;
for(int i = 0 ; i < len ; ++i)
{
ms.insert(nums[i]) ;
if(i >= k-1)
{
ans.push_back(*ms.rbegin()) ;
auto it = ms.find(nums[i - k + 1]) ;
ms.erase(it) ;
}
}
return ans ;
}
};
解法二:
因为我们其实是想维持某段区间中的最大值,次大值.......所以可以用单调队列来做。
class MonotonicQueue{
public :
MonotonicQueue() = default ;
void push(int e)
{
while(!q.empty() && q.back() < e) q.pop_back() ;
q.push_back(e) ;
}
void pop()
{
q.pop_front() ;
}
int max()
{
return q.front() ;
}
private:
deque<int> q ;
};
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k)
{
int len = nums.size() ;
MonotonicQueue MQ ;
vector<int> res ;
for(int i = 0 ; i < len ; ++i)
{
MQ.push(nums[i]) ;
if(i >= k - 1)
{
res.push_back(MQ.max()) ;
if(nums[i - k + 1] == MQ.max()) MQ.pop() ;
}
}
return res ;
}
};