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

2019-05-02  本文已影响0人  CoderJed

1. 题目要求

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

2. 思路1

3. 思路1 Java代码实现

public static class MyStack1 {

        private Stack<Integer> dataStack;
        private Stack<Integer> 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<Integer> dataStack;
        private Stack<Integer> 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;
        }

}
上一篇下一篇

猜你喜欢

热点阅读