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

package com.fiberhome.monitor.task;

import java.util.Stack;

public class SolutionStack {

    private Stack stack = new Stack();//所有的值都进入这个栈
    private Stack minStack = new Stack();//最小值栈,降序排
    private Stack maxStack = new Stack();//最大值栈.,升序排

    public void push(int node) {
        stack.push(node);//不管什么值,都入栈
        if(maxStack.isEmpty() || minStack.isEmpty()){//如果大小栈为空,统一入栈
            maxStack.push(node);
            minStack.push(node);
        }else{
            if(node <= minStack.peek()){//比小栈最小的还小,压入小栈
                minStack.push(node);
            }else if(node >= maxStack.peek()){//比大栈最大的还大,压入大栈
                maxStack.push(node);
            }
        }

    }

    public void pop() {
        if(stack.peek()==minStack.peek()){//需要弹出的值=最小值的顶端值,最小栈也应弹出
            minStack.pop();
        }else if(stack.peek() == maxStack.peek()){//需要弹出的值=最大值的顶端值,最大栈也应弹出
            maxStack.pop();
        }
        stack.pop();//值栈弹出
    }

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

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

    public static void main(String[] args) {
        SolutionStack stack = new SolutionStack();
        stack.push(5);
        stack.push(3);
        stack.push(7);
        stack.push(4);stack.push(2);stack.push(9);stack.push(1);

        int i = stack.min();
        System.out.println(i);

    }
}

你可能感兴趣的:(剑指offer算法)