这是一道被锁住的题,需要LeetCode会员才能做。
还好lintcode上也有。最大栈
分析:前4个操作比较简单,最难处理的是第5个操作。
思路:
1.可以使用两个栈,但是这样的复杂度为O(n),不太好。
2.使用list+map,list中存放数据,map中存放值以及值对应的所有迭代器的集合,迭代器的集合使用vector存储,vector尾部的迭代器为当前值对应的最靠近栈顶的迭代器,那么我们在删除栈中最靠近栈顶的最大元素时,只需要获得最大值对应vector的最后一个元素(迭代器),然后在list和vector中将其删除即可。
class MaxStack {
public:
/** initialize your data structure here. */
MaxStack() {}
void push(int x) {
list.insert(list.begin(), x);//插入到表头
map[x].push_back(list.begin());
}
int pop() {
auto x = *list.begin();
map[x].pop_back(); //删除map中的迭代器
if(map[x].empty()){
map.erase(x);
}
list.erase(list.begin());
return x;
}
int top() {
return *list.begin();
}
int peekMax() {
return map.rbegin()->first;//最大值
}
int popMax() {
auto x = map.rbegin->first;//最大值
auto it = map[x].back();//最大值中最靠近栈顶的迭代器
map[x].pop_back();//删除该迭代器
if(map[x].empty()){
map.erase(x);
}
list.erase(it);
return x;
}
private:
list<int> list;//存放数据
map<int, vector<list<int>::iterator>> map;//vector为相同值的迭代器集合,尾部的为最靠近栈顶的
};