第20题——包含min函数的栈

116 阅读1分钟

题目:

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

思路:

利用辅助栈

Java

package nowcoder;

import java.util.Stack;

public class S20_MinStack {
    Stack<Integer> stack = new Stack<Integer>();
    Stack<Integer> minStack = new Stack<Integer>();
    public void push(int node){
        if (minStack.isEmpty() || minStack.peek() > node)
            minStack.push(node);
        else minStack.push(minStack.peek());
    }
    public void pop(){
        stack.pop();
        minStack.pop();
    }
    public int peek(){
        return stack.peek();
    }
    public int min(){
        return minStack.peek();
    }
}

Python

class MinStack:
    stack = []
    minStack = []
    def push(self, node):
        if not self.minStack or node < self.minStack[-1]:
            self.minStack.append(node)
        else:
            self.minStack.append(self.minStack[-1])
    def pop(self):
        if not self.stack:
            return None
        self.minStack.pop()
        return self.stack.pop()
    def peek(self):
        if not self.stack:
            return None
        return self.stack[-1]
    def min(self):
        if not self.minStack:
            return None
        return self.minStack[-1]