Stack comprising the min function AcWing

Stack comprising the min function AcWing

Description

  • A support designed to push, pop, top and other operations can be retrieved stack smallest element in O (1) time.
    • push (x) - the stack is inserted into the element x
    • pop () - remove the top element
    • top () - get the top element
    • getMin () - get the minimum element in the stack

other:

  • This question is very unique sample input and output(Strange), Turn link

answer:

  • Stack.
  • First, the first three are stacks of normal operation. After the first four operations can be done slightly Consideration found: storage at a data structure with each historical time minimum, so that the stack may be performed after the reduction .
  • So choose stacks slightly. Specific stack is to open a new record minimum every time. Original stack directly inserted into the insert elements, newly inserted stack max (new stack top, element). When the original stack pop stack with new pop-top can be.
  • Complexity of O (1), very good.
//这题题目给了一个类似封装的东西,你只需要往相应的地方填代码就好了。在C++编译不过没关系
class MinStack {
public:
    /** initialize your data structure here. */
    stack<int> stk1, stk2;
    MinStack() {
        
    }
    
    void push(int x) {
        stk1.push(x);
        if(!stk2.size()) stk2.push(x);
        else stk2.push(min(x, stk2.top()));
    }
    
    void pop() {
        stk1.pop(), stk2.pop();
    }
    
    int top() {
        return stk1.top();
    }
    
    int getMin() {
        return stk2.top();
    }
};

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

Guess you like

Origin www.cnblogs.com/BigYellowDog/p/11300680.html