【力扣面试】面试题 03.05. 栈排序

【力扣面试】面试题 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值