从大到小排列:
原数组push到栈a,栈b为空。此为初始状态。
如果栈为空,栈a顶弹出,压入栈b。如果栈a顶大于栈b顶,接着栈a顶弹出,压入栈b。
如果栈a顶小于栈b顶,则栈a顶弹出,保存为临时变量,一个一个从栈b弹出元素临时移动到栈a,直到这个临时变量大于栈b顶,此时压入栈b,再将刚才移动到栈a的元素弹出恢复压入到栈b。直到栈a为空。
class TwoStacks {
public:
vector<int> twoStacksSort(vector<int> numbers) {
// write code here
stack<int> a;
stack<int> b;
for (int i = numbers.size() - 1; i >= 0; i--){
a.push(numbers[i]);
}
while (!a.empty())
{
if (b.empty() || a.top()>b.top()){
b.push(a.top());
a.pop();
}
else{
int n = a.top(), m = 0;
a.pop();
while (!b.empty() && n<b.top()){
a.push(b.top());
b.pop();
++m;
}
b.push(n);
while (m--){
b.push(a.top());
a.pop();
}
}
}
vector<int>c;
while (!b.empty()){
c.push_back(b.top());
b.pop();
}
return c;
}
};