3.6 题目:
对栈进行排序,要求最大的值存放在栈顶。
基础:只能使用一个额外的栈存储临时数据。
进阶:
允许使用多个栈或其他数据结构,将时间复杂度优化为O(nlog(n))
解法:
基础解法,下面画图分步骤说明:
初始状态:S1为未排序的栈,S2为空栈
S1 | S2 |
---|---|
5 | null |
10 | null |
7 | null |
弹出栈顶元素5,发现S2为空,直接放进去
S1 | S2 |
---|---|
null | null |
10 | null |
7 | 5 |
弹出栈顶元素10,S2不为空,对比S2的栈顶元素5,发现大于5,可以直接放入
S1 | S2 |
---|---|
null | null |
null | 10 |
7 | 5 |
弹出栈顶元素7,S2不为空,对比S2的栈顶元素10,发现小于10,把10弹出放入S1
然后接着对比7和新的栈顶元素5,发现小于5,放入即可。
S1 | S2 |
---|---|
null | null |
null | 7 |
10 | 5 |
弹出S1栈顶元素10,S2不为空,10大于S2的栈顶元素7,直接放入。
S1 | S2 |
---|---|
null | 10 |
null | 7 |
null | 5 |
代码如下:
public static Stack<Integer> sort(Stack<Integer> s){
Stack<Integer> result = new Stack<Integer>();
while(!s.isEmpty()){
Integer value = s.pop();
while(!result.isEmpty() && result.peek() > value){
s.push(result.pop());
}
result.push(value);
}
return result;
}
该解法的时间复杂度为O(N^2) 空间复杂度为O(N)
进阶解法
1、如果允许使用数组,可以把栈复制为数据,然后使用JDK的Arrays.sort 方法,进行排序即可
代码如下:
public static void stackToArraySort(Stack<Integer> s){
Object[] anArray = new Object[s.size()];
s.copyInto(anArray);
Arrays.sort(anArray);
for(int i = 0;i<s.size();i++){
s.set(i, (Integer)anArray[i]);
}
}
2、自己实现一个快速排序
代码如下:
public static Stack<Integer> quickSort(Stack<Integer> s){
qSort(s,0,s.size()-1);
return s;
}
private static void qSort(Stack<Integer> s, int low, int high) {
int pivot;
if(low<high){
pivot = partition(s,low,high);
qSort(s,low,pivot-1);
qSort(s,pivot+1,high);
}
}
private static int partition(Stack<Integer> s, int low, int high) {
int pivotKey = s.get(low);
while(low < high){
while(low < high && s.get(high)>=pivotKey)
high--;
swap(s,low,high);
while(low < high && s.get(low)<= pivotKey)
low++;
swap(s,low,high);
}
return low;
}
private static void swap(Stack<Integer> s, int low, int high) {
int temp = s.get(low);
s.set(low,s.get(high));
s.set(high, temp);
}
关于快速排序的原理,可以参考其他资料,这里不再赘述。