[Sword Finger 30] A stack containing the min function

Method 1: Dual stack simulation minimum stack: time O(1), space O(n)

answer:

  1. To ensure that the time complexity of push(), pop(), min() and other functions are all O(1), so we manage a minimum stack dedicated to storing the smallest value in the current stack
  2. push(): Push directly into the stack, min stack: Determine the size of the top element and the inserted element, and insert if the inserted element is smaller or equal
  3. pop(): directly delete the push stack, min stack: determine whether the top element of the stack is the same as the element deleted by the push stack, delete if the same
    Insert picture description here
class MinStack {
    
    
    private:
    stack<int> push_stc;
    stack<int> min_stc;
public:
    /** initialize your data structure here. */
    MinStack() {
    
    

    }
    
    void push(int x) {
    
    
        push_stc.push(x);
        if (min_stc.empty() || min_stc.top() >= x)
        {
    
    
            min_stc.push(x);
        }
    }
    
    void pop() {
    
    
        if (push_stc.empty())
            return;
        if (push_stc.top() == min_stc.top())
            min_stc.pop();
        push_stc.pop();
    }
    
    int top() {
    
    
        if (push_stc.empty())
            return -1;
        return push_stc.top();
    }
    
    int min() {
    
    
        if (min_stc.empty())
            return -1;
        return min_stc.top();
    }
};

Guess you like

Origin blog.csdn.net/qq_45691748/article/details/113867643