716. Max Stack
MaxStack stack = new MaxStack();
stack.push(5);
stack.push(1);
stack.push(5);
stack.top(); ->5
stack.popMax(); ->5
stack.top(); ->1
stack.peekMax(); ->5
stack.pop(); ->1
stack.top(); ->5Last updated
Was this helpful?
MaxStack stack = new MaxStack();
stack.push(5);
stack.push(1);
stack.push(5);
stack.top(); ->5
stack.popMax(); ->5
stack.top(); ->1
stack.peekMax(); ->5
stack.pop(); ->1
stack.top(); ->5Last updated
Was this helpful?
Was this helpful?
class MaxStack {
public:
/** initialize your data structure here. */
list<int> l;
map<int, vector<list<int>::iterator>> mp;
MaxStack() {
}
void push(int x) {
l.insert(l.begin(),x);
mp[x].push_back(l.begin());
}
int pop() {
// delete iterator in the map
int key = *l.begin();
mp[key].pop_back();
if(mp[key].empty()) mp.erase(key);
l.erase(l.begin());
return key;
}
int top() {
return *l.begin();
}
int peekMax() {
return mp.rbegin()->first;
}
int popMax() {
int key = mp.rbegin()->first;
// get the iterator
auto it = mp[key].back();
mp[key].pop_back();
if(mp[key].empty()) mp.erase(key);
l.erase(it);
return key;
}
};