LeetCode 打卡
队列的最大值
class MaxQueue {
private:
queue<int> q;
deque<int> tempMax;
public:
MaxQueue() {
}
int max_value() {
if(tempMax.empty())
return -1;
return tempMax.front();
}
void push_back(int value) {
while(!tempMax.empty() && tempMax.back()<value)
{
tempMax.pop_back();
}
tempMax.push_back(value);
q.push(value);
}
int pop_front() {
if(q.empty())
return -1;
int res=q.front();
if(res==tempMax.front())
{
tempMax.pop_front();
}
q.pop();
return res;
}
};
滑动窗口的最大值
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> res;
deque<int> tempResIndex;
for(int right=0;right<nums.size();right++)
{
while(!tempResIndex.empty() && nums[right]>=nums[tempResIndex.back()])
{
tempResIndex.pop_back();
}
tempResIndex.push_back(right);
int left=right-k+1;
if(tempResIndex.front()<left)
{
tempResIndex.pop_front();
}
if(right+1>=k)
{
res.emplace_back(nums[tempResIndex.front()]);
}
}
return res;
}
};