题意:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
要求:得到最小值元素的min时间复杂度要求为O(1)
思想:利用额外的栈来记录当前的最小值,如果当前push的元素比当前helper栈中的元素小或等于将其push到helper栈中(注意对于等于的处理,因为要在出栈的时候做出栈使用)
实现:
class MinStack {
private:
stack<int> _realStack;
stack<int> _helperStack;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
_realStack.push(x);
if(_helperStack.empty() || _helperStack.top() >= x){
_helperStack.push(x);
}
}
void pop() {
int temp = _realStack.top();
_realStack.pop();
if(!_helperStack.empty() && _helperStack.top() == temp)
_helperStack.pop();
}
int top() {
return _realStack.top();
}
int min() {
return _helperStack.top();
}
};
题意:
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
要求:max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)
思想:利用额外的双端队列来管理最大值
实现:
class MaxQueue {
queue<int> _queue;
deque<int> _deque;
public:
MaxQueue() {
}
int max_value() {
if(_deque.empty())
return -1;
return _deque.front();
}
void push_back(int value) {
//push_back时需要保证_deque中保存的是当前_queue的最大值
while(!_deque.empty() && _deque.back() < value){
_deque.pop_back();
}
_deque.push_back(value);
_queue.push(value);
}
int pop_front() {
if(_queue.empty()) return -1;
//弹出很好理解,如果当前的最大值pop,需要将_deque中的去除
int value = _queue.front();
if(value == _deque.front()){
_deque.pop_front();
}
_queue.pop();
return value;
}
};