【力扣面试】面试题 03.05. 栈排序
题目
栈排序。 编写程序,对栈进行排序使最小元素位于栈顶。最多只能使用一个其他的临时栈存放数据,但不得将元素复制到别的数据结构(如数组)中。该栈支持如下操作: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]
解题思路
方法一:
使用优先队列做法,利用PriorityQueue的特性,使用比较函数,将数据从小到大存储在优先队列中。
代码
class SortedStack {
PriorityQueue<Integer> priorityQueue;
public SortedStack() {
priorityQueue = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
}
public void push(int val) {
priorityQueue.add(val);
}
public void pop() {
priorityQueue.poll();
}
public int peek() {
if (!isEmpty()) {
return priorityQueue.peek();
} else {
return -1;
}
}
public boolean isEmpty() {
return priorityQueue.isEmpty();
}
}
优先队列做法:
方法二:
解题思路:
1、始终维持栈元素从小到大的顺序;
2、每次push,寻找第一个大于等于val的位置处插入;
3、临时栈只用于暂存该位置之上的元素。
代码
class SortedStack {
Stack<Integer> stack;
Stack<Integer> tempStack;
public SortedStack() {
stack = new Stack<>();
tempStack = new Stack<>();
}
public void push(int val) {
//找到合适的位置,插入val
while (!stack.isEmpty() && stack.peek() < val) {
tempStack.push(stack.pop());
}
stack.push(val);
//将暂存在tempstack中的元素重新复原到stack中
while (!tempStack.isEmpty()){
stack.push(tempStack.pop());
}
}
public void pop() {
if (!stack.isEmpty()){
stack.pop();
}
}
public int peek() {
if (!stack.isEmpty()){
return stack.peek();
}
return -1;
}
public boolean isEmpty() {
return stack.isEmpty();
}
}
使用两个栈
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-of-stacks-lcci