包含min函数的栈

2018/10/20 Offer 共 610 字,约 2 分钟

title

problem link

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

solution

public class Solution {
    Stack<Integer> stack=new Stack<>();
    Stack<Integer> minStack=new Stack<>();
    public void push(int node) {
        stack.push(node);
        if(minStack.isEmpty())
            minStack.push(node);
        else
            minStack.push(Math.min(minStack.peek(),node));
    }

    public void pop() {
        stack.pop();
        minStack.pop();
    }

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

    public int min() {
        return minStack.peek();
    }

    public static void main(String[] args) {
        Solution solution=new Solution();
        solution.push(3);
        System.out.println(solution.min());
        solution.push(4);
        System.out.println(solution.min());
    }

Search

    Table of Contents