请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
示例 1:
输入:
[“MaxQueue”,“push_back”,“push_back”,“max_value”,“pop_front”,“max_value”]
[[],[1],[2],[],[],[]]
输出: [null,null,null,2,1,2]
示例 2:
输入:
[“MaxQueue”,“pop_front”,“max_value”]
[[],[],[]]
输出: [null,-1,-1]
限制:
1 <= push_back,pop_front,max_value的总操作数 <= 10000
1 <= value <= 10^5
瞎写的,时间复杂度爆炸,但是过了
class MaxQueue {
public:
vector<int> nums;
MaxQueue() {
}
int max_value() {
if(nums.size() == 0)
return -1;
int max_num = -1;
for(int num : nums){
if(num > max_num)
max_num = num;
}
return max_num;
}
void push_back(int value) {
nums.push_back(value);
}
int pop_front() {
if(nums.size() == 0) return -1;
vector<int> temp;
int res = nums[0];
for(int i = 1; i < nums.size(); i++){
temp.push_back(nums[i]);
}
nums.swap(temp);
return res;
}
};
/**
* 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 {
int q[20000];
int begin = 0, end = 0;
public:
MaxQueue() {
}
int max_value() {
int ans = -1;
for (int i = begin; i != end; ++i)
ans = max(ans, q[i]);
return ans;
}
void push_back(int value) {
q[end++] = value;
}
int pop_front() {
if (begin == end)
return -1;
return q[begin++];
}
};
使用deque做一个双端队列用来找最大值,使用queue做一个普通队列用来pop_front,假设普通队列是132458,在pop_front前几个数时,最大值一直是8,只有8pop出去的时候最大值才会改变,因此记录最大值的双端队列中
空 < 1
1 < 3 进来的是3,比1大,就把1出去
3 < 2
32 < 4 进来的是4,比前两个都大
4 < 5
5 < 8
8
而插入操作虽然看起来有循环,做一个插入操作时最多可能会有 nn 次出队操作。但要注意,由于每个数字只会出队一次,因此对于所有的 nn 个数字的插入过程,对应的所有出队操作也不会大于 nn 次。因此将出队的时间均摊到每个插入操作上,时间复杂度为 O(1)O(1)。
class MaxQueue {
public:
queue<int> q;
deque<int> d;
MaxQueue() {
}
int max_value() {
if(q.size() == 0)
return -1;
return d.front();
}
void push_back(int value) {
q.push(value);
while(!d.empty() && d.back() < value){
d.pop_back();
}
d.push_back(value);
}
int pop_front() {
if(q.size() == 0)
return -1;
int res = q.front();
q.pop();
if(res == d.front()){
d.pop_front();
}
return res;
}
};
/**
* 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();
*/