【LeetCode刷题记录】26.栈排序

193 阅读1分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

一、题目描述:

题目来源:LeetCode-栈排序

栈排序。 编写程序,对栈进行排序使最小元素位于栈顶。

最多只能使用一个其他的临时栈存放数据,但不得将元素复制到别的数据结构(如数组)中。

该栈支持如下操作: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]

说明:

栈中的元素数目在[0, 5000]范围内。

二、思路分析:

思路一:

输入值如果大于栈顶值,则把栈顶弹出,用临时变量保存,继续往下。

当输入值不大于栈顶值或栈已空时,把输入值压入栈,将每一步的临时变量存的值依次压回栈。

思路二:

使用一个临时栈存放数据

入栈时,先将栈中小于val的数值暂存到临时栈中

将val入栈

再将临时栈中的数据push会栈中

三、AC 代码:

思路一:


    class SortedStack {
        Stack<Integer> stack;

        public SortedStack() {
            stack = new Stack<Integer>();
        }

        public void push(int value) {
            sort(value);
        }

        public void pop() {
            if (stack.isEmpty()) return;

            stack.pop();
            return;
        }

        public int peek() {
            if (stack.isEmpty()) return -1;

            return stack.peek();
        }

        public boolean isEmpty() {
            return stack.isEmpty();
        }

        private void sort(int value) {
            if (stack.isEmpty() || value < stack.peek()) {
                stack.push(value);
                return;
            } else {
                int tempValue = stack.pop();
                sort(value);
                stack.push(tempValue);
            }
        }
    }

思路二:

    public class SortedStack {
        private Deque<Integer> stack;
        private Deque<Integer> tempStack;

        public SortedStack() {
            stack = new LinkedList<>();
            tempStack = new LinkedList<>();
        }

        public void push(int val) {
            if (isEmpty()) {
                stack.push(val);
            } else {
                while (!stack.isEmpty() && val > stack.peek()) {
                    tempStack.push(stack.pop());
                }
                stack.push(val);
                while (!tempStack.isEmpty()) {
                    stack.push(tempStack.pop());
                }
            }
        }

        public void pop() {
            if (stack.isEmpty()) {
                return;
            }
            stack.pop();
        }

        public int peek() {
            if (stack.isEmpty()) {
                return -1;
            }
            return stack.peek();
        }

        public boolean isEmpty() {
            return stack.isEmpty();
        }
    }