题目来源:79. 滑动窗口的最大值
代码:
class Solution
{
public:
vector<int> maxInWindows(vector<int> &nums, int k)
{
priority_queue<pair<int, int>> pq;
// 初始化
for (int i = 0; i < k; i++)
pq.push(make_pair(nums[i], i));
vector<int> ans;
ans.push_back(pq.top().first);
// 遍历
for (int i = k; i < nums.size(); i++)
{
pq.push(make_pair(nums[i], i));
while (!pq.empty() && pq.top().second <= i - k)
pq.pop();
ans.push_back(pq.top().first);
}
return ans;
}
};
复杂度分析:
时间复杂度:O(n),其中 n 是数组 nums 的长度。
空间复杂度:O(n),其中 n 是数组 nums 的长度。
class Solution
{
public:
vector<int> maxSlidingWindow(vector<int> &nums, int k)
{
deque<int> dq;
vector<int> ans;
for (int i = 0; i < nums.size(); i++)
{
if (!dq.empty() && dq.front() == i - k)
dq.pop_front();
while (!dq.empty() && nums[dq.back()] < nums[i])
dq.pop_back();
dq.push_back(i);
if (i >= k - 1)
ans.push_back(nums[dq.front()]);
}
return ans;
}
};
复杂度分析:
时间复杂度:O(n),其中 n 是数组 nums 的长度。
空间复杂度:O(n),其中 n 是数组 nums 的长度。
题目描述:请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的时间复杂度都是O(1)。若队列为空,pop_front 和 max_value 需要返回 -1。
算法:
代码:
/**
* Your MaxQueue object will be instantiated and called as such:
* MaxQueue* obj = new MaxQueue();
* int param_1 = obj->max_value();
* obj->push_back(value);
* int param_3 = obj->pop_front();
*/
class MaxQueue {
public:
MaxQueue() {
}
int max_value() {
if (helpQueue.empty()) {
return -1;
}
return helpQueue.front();
}
void push_back(int value) {
queue.push(value);
while (!helpQueue.empty() && helpQueue.back() < value) {
helpQueue.pop_back();
}
helpQueue.push_back(value);
}
int pop_front() {
if (queue.empty()) {
return -1;
}
int front = queue.front();
queue.pop();
if (front == helpQueue.front()) {
helpQueue.pop_front();
}
return front;
}
private:
queue<int> queue;
deque<int> helpQueue;
};
复杂度分析:
时间复杂度:
空间复杂度:O(n),其中 n 是插入元素的个数。