<Prove safety offer> 18 title

topic:

Stack data structure definition, the type realized in a stack to find the minimum number min function, in the stack, call min, Push, pop time complexity is O (1)

Ideas:

Each of the smallest element (both elements of the smallest element pushed onto the stack before and the new smaller value) are saved into another assisted the stack.

If every time the smallest element pressed into the auxiliary stack, the stack will be able to save the auxiliary stack has always been the smallest element, when the minimum element is popped from the data stack, and pop the top element of the auxiliary stack, this time assisted the new top element of the stack is the next minimum

Code:

import java.util.Stack;

public class Eighteenth {
    private Stack<Integer> stack = new Stack<>();
    private Stack<Integer> minStack = new Stack<>();
    
    public void push(int data){
        stack.push(data);
        if(minStack.size() == 0 || data < minStack.peek()){
            minStack.push(data);
        }else{
            minStack.push(minStack.peek());
        }
    }
    
    public int pop() throws Exception{
        if(stack.size() == 0){
            throw new Exception("栈已为空");
        }
        int data = stack.pop();
        minStack.pop();
        return data;
    }
    
    public int min() throws Exception{
        if(stack.size() == 0){
            throw new Exception("栈已为空");
        }
        return minStack.peek();
    }
}

 

Guess you like

Origin www.cnblogs.com/HarSong13/p/11330712.html