面试题 03.05. 栈排序

这篇博客探讨了如何使用单调栈来保持栈内的元素始终有序。作者提供了两种不同的实现方式,第一种是每次push时调整栈内元素顺序,第二种则是采用惰性更新策略,仅在pop时进行调整。这两种方法都在C++中进行了实现,并且在执行时间和内存消耗上都有较好的表现。

题目链接: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的时候才全部换到栈中
压栈时保证vals.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();
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值