[算法题] 实现一个特殊的栈,在基本栈的基础上,增加返回栈中最小元素的方法

1. 题目要求

实现一个特殊的栈,在栈的基本功能的基础上,增加一个功能:返回栈中最小元素
要求:

  • pop(),push(),getMin()操作的复杂度都为O(1)
  • 设计的栈类型可以使用现成的栈结构

2. 思路1

3. 思路1 Java代码实现

public static class MyStack1 {

        private Stack dataStack;
        private Stack minStack;

        public MyStack1() {
            this.dataStack = new Stack<>();
            this.minStack = new Stack<>();
        }

        public int getMin() {
            if(minStack.isEmpty()) {
                throw new RuntimeException("Your stack is empty!");
            }
            return minStack.peek();
        }

        public void push(int element) {
            if(minStack.isEmpty()) {
                minStack.push(element);
            } else if(element <= getMin()) {
                minStack.push(element);
            } else {
                int min = minStack.peek();
                minStack.push(min);
            }
            dataStack.push(element);
        }

        public int pop() {
            if(dataStack.isEmpty()) {
                throw new RuntimeException("Your stack is empty!");
            }
            minStack.pop();
            return dataStack.pop();
        }

}

4. 思路2

思路2对思路1进行了空间上的优化,在思路1中可能会压入重复的元素,优化思路如下:


5. 思路2 Java代码实现

public static class MyStack2 {

        private Stack dataStack;
        private Stack minStack;

        public MyStack2() {
            this.dataStack = new Stack<>();
            this.minStack = new Stack<>();
        }

        public int getMin() {
            if(minStack.isEmpty()) {
                throw new RuntimeException("Your stack is empty!");
            }
            return minStack.peek();
        }

        public void push(int element) {
            if(minStack.isEmpty()) {
                minStack.push(element);
            } else if(element <= getMin()) {
                minStack.push(element);
            } // 只有当push的元素小于minStack的栈顶元素时才minStack才push
            dataStack.push(element);
        }

        public int pop() {
            if(dataStack.isEmpty()) {
                throw new RuntimeException("Your stack is empty!");
            }
            int value = dataStack.pop();
            // 只有dataStack的栈顶元素=minStack的栈顶元素时,minStack才弹出
            if(value == getMin()) {
                minStack.pop();
            }
            return value;
        }

}

你可能感兴趣的:([算法题] 实现一个特殊的栈,在基本栈的基础上,增加返回栈中最小元素的方法)