剑指Offer面试题21 & Leetcode155

剑指Offer面试题21 & Leetcode155

Min Stack  包含min函数的栈

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • getMin() – Retrieve the minimum element in the stack.

解题思路

  考虑:在最小栈的数据结构中维护两个栈,第一个栈为基础栈,维护栈的先入后出的特性。第二个栈为最小值栈,维护实现输出栈中最小值的功能。当进行push操作时,比较要push的值和min栈栈顶元素的值,如果小于等于栈顶元素的值,则在push进基础栈的同时将要push的值也push进min栈,这样能够保证min栈的栈顶元素始终是栈中的最小元素。在进行pop操作时,如过基础栈中pop出了最小值,要记得在min栈中也将其pop出。

Solution1 剑指Offer

public class MinStack {

        Stack stack = new Stack();
        Stack min_stack = new Stack();
        /** initialize your data structure here. */
        public MinStack() {

        }

        public void push(int x) {
            if(min_stack.isEmpty() || (!min_stack.isEmpty() && x<=min_stack.peek())){
                min_stack.push(x);
            }
            stack.push(x);
        }

        public void pop() {
            if(min_stack.peek().equals(stack.peek())){
                min_stack.pop();
            }
            stack.pop();
        }

        public int top() {
            return stack.peek();
        }

        public int getMin() {
            return min_stack.peek();
        }
}

你可能感兴趣的:(剑指offer-java实现,leetcode-java)