Prove safety Offer: min function comprising a stack (java version)

Title Description

Stack data structure definition, implement this type can be a min function smallest elements contained in the stack (should the time complexity O (1)).

analysis

With two stacks, one stack for normal memory ST1, the other is used to save the current minimum st2.
Logic is: if st2 top of the stack into the stack to be larger than the number, it ST1, st2 are added; if this number is less than the top of the stack st2, st2 to add one of their top element

public class Solution {
    Stack<Integer> st1=new Stack<Integer>();
    Stack<Integer> st2=new Stack<Integer>();
    public void push(int node) {
        st1.push(node);
        if(!st2.empty()){
            if(node>st2.peek()){
                st2.push(st2.peek());
            }else{
                st2.push(node);
            }
        }else{
            st2.push(node);
        }
    }  
    public void pop() {
        if(st1.empty())
            throw new RuntimeException("Your stack is empty.");
        st2.pop();
        st1.pop();
    }   
    public int top() {
        if(st1.empty())
            throw new RuntimeException("Your stack is empty.");
        return st1.peek();
    }   
    public int min() {
         if(st1.empty())
            throw new RuntimeException("Your stack is empty.");
         return st2.peek();
    }
}

optimization

The auxiliary stack is the minimum of the index storage (so do not keep repeating the minimum value, an index only memory)

public class MinStack {
    private List<Integer> data = new ArrayList<Integer>();
    private List<Integer> mins = new ArrayList<Integer>();
    public void push(int num) {
        data.add(num);
        if(mins.size() == 0) {
            // 初始化mins
            mins.add(0);
        } else {
            // 辅助栈mins push最小值的索引
            int min = getMin();
            if (num < min) {
                mins.add(data.size() - 1);
            }
        }
    }
    public int pop() {
        // 栈空,抛出异常
        if(data.size() == 0) {
            throw new EmptyStackException();
        }
        // pop时先获取索引
        int popIndex = data.size() - 1;
        // 获取mins栈顶元素,它是最小值索引
        int minIndex = mins.get(mins.size() - 1);
        // 如果pop出去的索引就是最小值索引,mins才出栈
        if(popIndex == minIndex) {
            mins.remove(mins.size() - 1);
        }
        return data.remove(data.size() - 1);
    }
    public int getMin() {
        // 栈空,抛出异常
        if(data.size() == 0) {
            throw new EmptyStackException();
        }
        // 获取mins栈顶元素,它是最小值索引
        int minIndex = mins.get(mins.size() - 1);
        return data.get(minIndex);
    }
}

Guess you like

Origin blog.csdn.net/qq_43165002/article/details/93716192