Challenge one leetocde question a day (sword refers to Offer 30. Stack containing min function) 0 basis

1. Topic

To define the data structure of the stack, please implement a min function that can get the smallest element of the stack in this type. In this stack, the time complexity of calling min, push and pop is O(1).

 MinStack minStack = new MinStack();
 minStack.push(-2);
 minStack.push(0);
 minStack.push(-3);
 minStack.min();   --> 返回 -3.
 minStack.pop();
 minStack.top();      --> 返回 0.
 minStack.min();   --> 返回 -2.

2. Idea

Key point
1. When the top of stack 1 is popped as the minimum value, the minimum value of the whole stack will also be popped.
Therefore, the minimum value also constitutes a stack 2. When the top of stack 1 is pushed as the minimum value, the minimum value stack 2 is also pushed; when the top of stack 1 is used as the minimum value pop, the minimum value stack 2 is also popped.

First of all, two stacks can be used, one
can be used as a minimum value stack, or one stack can be used for both purposes. . . Each entry and exit brings the minimum value and the top element of the stack, and uses two stack frames at a time.

3. Code

class MinStack {
    
    
    Stack<Integer> A, B;
    public MinStack() {
    
    
        A = new Stack<>();
        B = new Stack<>();
    }
    public void push(int x) {
    
    
        A.add(x);
        if(B.empty() || B.peek() >= x)
            B.add(x);
    }
    public void pop() {
    
    
        if(A.pop().equals(B.peek()))
            B.pop();
    }
    public int top() {
    
    
        return A.peek();
    }
    public int min() {
    
    
        return B.peek();
    }
}


4. Selected comments and problem-solving ideas

class MinStack {
    
    
    private Stack<Integer> dataStack; // 数据栈
    private Stack<Integer> minStack; // 辅助栈,记录每次有元素进栈后或者出栈后,元素的最小值
    /** initialize your data structure here. */
    public MinStack() {
    
    
        // 初始化辅助栈和数据栈
        dataStack = new Stack<>();
        minStack = new Stack<>();
    }
    public void push(int x) {
    
    
        // 如果记录当前数据栈中最小值的辅助栈为空,或者最小值小于 x,则将 x 设置为最小值,即进辅助栈
        if(minStack.isEmpty() || minStack.peek() > x){
    
    
            minStack.push(x);
        }else{
    
    // 如果数据栈中当前最小值 < x, 则继续将最小值设置为上次的最小值
            minStack.push(minStack.peek());
        }
        dataStack.push(x);// 数据栈,进栈
    }

    public void pop() {
    
    
        minStack.pop();// 辅助栈,栈出栈
        dataStack.pop();// 数据栈,出栈
    }

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

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


Guess you like

Origin blog.csdn.net/leader_song/article/details/123464599