栈排序。 编写程序,对栈进行排序使最小元素位于栈顶。最多只能使用一个其他的临时栈存放数据,但不得将元素复制到别的数据结构(如数组)中。该栈支持如下操作:push、pop、peek 和 isEmpty。当栈为空时,peek 返回 -1。
示例1:
输入:
[“SortedStack”, “push”, “push”, “peek”, “pop”, “peek”]
[[], [1], [2], [], [], []]
输出:
[null,null,null,1,null,2]
示例2:
输入:
[“SortedStack”, “pop”, “pop”, “push”, “pop”, “isEmpty”]
[[], [], [], [1], [], []]
输出:
[null,null,null,null,null,true]
** 解题思路**
- 暴力解法
题目要求要维护一个排好序的栈,则意味这在每次栈中元素数目变化后,即pop或push后,栈仍然是一个排序栈,pop不影响,push需要考虑,最简单的方法就是插入,即将要push的值插入到栈中对应位置,维护排序栈。将小于val的值放入辅助栈,push(val),然后再从辅助栈中将其他元素挪回。
class SortedStack {
Stack<Integer> stack, temp;
public SortedStack() {
stack = new Stack<>();
temp = new Stack<>();
}
public void push(int val) {
if (stack.isEmpty()) stack.push(val);
else {
while (!stack.isEmpty() && stack.peek() < val)
temp.push(stack.pop());
stack.push(val);
while (!temp.isEmpty())
stack.push(temp.pop());
}
}
public void pop() {
if (!stack.isEmpty()) stack.pop();
}
public int peek() {
if (stack.isEmpty()) return -1;
return stack.peek();
}
public boolean isEmpty() {
return stack.isEmpty();
}
}
- 优化算法
通过查看提示我们得知有可以优化的算法,具体思考,我们再push一个值需要将前面的元素移到辅助栈再移回来,我们可以同时维护辅助栈和数据栈来减少重复移动。
假设要push的元素为x:
- x小于数据栈的栈顶:将辅助栈大于x的移入数据栈,xpush到辅助栈。
- x大于数据栈的栈顶:将数据栈小于x的移入辅助栈,xpush到数据栈。
- 在执行pop及peek时需要合并栈。
class SortedStack {
Stack<Integer> stack, temp;
public SortedStack() {
stack = new Stack<>();
temp = new Stack<>();
}
public void push(int val) {
if (stack.isEmpty()) stack.push(val);
else {
if (stack.peek() > val) {
if (temp.isEmpty()) temp.push(val);
else {
while (!temp.isEmpty() && temp.peek() > val) stack.push(temp.pop());
temp.push(val);
}
} else {
while (!stack.isEmpty() && stack.peek() < val) temp.push(stack.pop());
stack.push(val);
}
}
}
public void pop() {
if (stack.isEmpty() && temp.isEmpty()) return;
while (!temp.isEmpty()) {
stack.push(temp.pop());
}
stack.pop();
}
public int peek() {
if (stack.isEmpty() && temp.isEmpty()) return -1;
while (!temp.isEmpty()) {
stack.push(temp.pop());
}
int res = stack.peek();
return res;
}
public boolean isEmpty() {
return stack.isEmpty()&&temp.isEmpty();
}
}