题目链接:leetcode.
越来越看不懂题,,人家都说了栈排序,我在这整啥单调栈呢
思路就是,用一个辅助栈每次倒腾,使得每次push的元素位于自己正确的位置
/*
执行用时:256 ms, 在所有 C++ 提交中击败了29.33%的用户
内存消耗:45.7 MB, 在所有 C++ 提交中击败了40.67%的用户
*/
class SortedStack {
stack<int> s;
stack<int> tmp;
public:
SortedStack() {
}
void push(int val) {
while(!s.empty() && s.top() < val)
{
tmp.push(s.top());
s.pop();
}
s.push(val);
while(!tmp.empty())
{
s.push(tmp.top());
tmp.pop();
}
}
void pop() {
if(!s.empty())
s.pop();
}
int peek() {
if(s.empty())
return -1;
return s.top();
}
bool isEmpty() {
return s.empty();
}
};
/**
* Your SortedStack object will be instantiated and called as such:
* SortedStack* obj = new SortedStack();
* obj->push(val);
* obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->isEmpty();
*/
惰性更新更优秀
辅助栈维护一个递增的数列,只有需要pop的时候才全部换到栈中
压栈时保证val比s.top()小,比tmp.top()大
/*
执行用时:24 ms, 在所有 C++ 提交中击败了73.67%的用户
内存消耗:11.7 MB, 在所有 C++ 提交中击败了82.67%的用户
*/
class SortedStack {
stack<int> s;
stack<int> tmp;
public:
SortedStack() {
}
void push(int val) {
//就这两个while,给我在那if else写的老访问越界,醉了
while(!s.empty() && s.top() < val)
{
tmp.push(s.top());
s.pop();
}
while(!tmp.empty() && tmp.top() > val)
{
s.push(tmp.top());
tmp.pop();
}
s.push(val);
}
void pop() {
if(tmp.empty() && s.empty())
return;
while(!tmp.empty())
{
s.push(tmp.top());
tmp.pop();
}
s.pop();
}
int peek() {
if(tmp.empty() && s.empty())
return -1;
while(!tmp.empty())
{
s.push(tmp.top());
tmp.pop();
}
return s.top();
}
bool isEmpty() {
return s.empty() && tmp.empty();
}
};
这篇博客探讨了如何使用单调栈来保持栈内的元素始终有序。作者提供了两种不同的实现方式,第一种是每次push时调整栈内元素顺序,第二种则是采用惰性更新策略,仅在pop时进行调整。这两种方法都在C++中进行了实现,并且在执行时间和内存消耗上都有较好的表现。
6487

被折叠的 条评论
为什么被折叠?



