要求:找出每连续k个元素的最大值
思路:暴力不行
法一:大根堆,存好值和下标,时间O(nlogn)空间O(n)
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
if(nums.size()==0)return {};
priority_queue<pair<int,int>> q;
vector<int> v;
for(int i=0;i<k;++i)
q.push(make_pair(nums[i],i));
for(int i=k;i<nums.size();++i){
v.push_back(q.top().first);
while(!q.empty()&&q.top().second<=i-k){
q.pop();
}
q.push(make_pair(nums[i],i));
}
v.push_back(q.top().first);
return v;
}
};
法二:双端队列,最小栈那题是同步另一个栈每次插入都存最小值,本题双端队列,首先一个前提是如果当前要插的大于队尾那队尾可以不要了,基于此队列是单调递减的,只要存下标,时间O(n),空间O(k)
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
if(nums.size()==0)return {};
deque<int> q;
vector<int> v;
for(int i=0;i<k;++i){
while(!q.empty()&&nums[q.back()]<=nums[i])q.pop_back();
q.push_back(i);
}
v.push_back(nums[q.front()]);
for(int i=k;i<nums.size();++i){
while(!q.empty()&&nums[q.back()]<=nums[i])q.pop_back();
q.push_back(i);
while(!q.empty()&&q.front()<=i-k)q.pop_front();
v.push_back(nums[q.front()]);
}
return v;
}
};