双栈排序
其实开始前我想吐槽一下,牛客网好多题目表述不清楚,比如说这双栈排序,我不明白为什么非要用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;
}
};