双栈排序

双栈排序

其实开始前我想吐槽一下,牛客网好多题目表述不清楚,比如说这双栈排序,我不明白为什么非要用vector来表示,这样给操作带来很大的不便,那如果要用栈的话,直接就stack不就好了,但是这个题目是这么要求的,只能按他的意思,将原有数据复制到一个栈,然后定义一个辅助栈,用两个栈进行排序,最后将辅助栈的结果又一个个赋值到结果vector,感觉好绕

思想用了别人的方法,我只是自己实现了一下。

题目及思想如下图所示:

代码如下:

class TwoStacks {
public:
    vector<int> twoStacksSort(vector<int> numbers) {
        // write code here
        stack<int> a,b;
        vector<int> res;
        int num=numbers.size();
        for(int i=0;i<num;i++)
            a.push(numbers[i]);
        b.push(a.top());
        a.pop();
        int tmp=0;
        int count=0;
        while(!a.empty())
        {
            count=0;
        	tmp=a.top();
            a.pop();
            while(!b.empty()&&b.top()>tmp)
            {
                //while(!b.empty()){
                    a.push(b.top());
                	b.pop();
                	count++;
                //}

            }
            b.push(tmp);
            while(count>0)
            {
            	b.push(a.top());
                a.pop();
                count--;
            }
            
        }
        while(!b.empty())
        {
            res.push_back(b.top());
            b.pop();
        }
        return res;
            
    }
};




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值