Offer prove safety [] [] stack comprising stack min function

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

 

A: As the stack and that the variable contains the operand stack, not just the minimum number of storage variable is just an int, you should be used to store a stack of secondary

  So create a data station storage stack to create the minimum number of stack memory the minimum number of

  Stack: the stack data in the stack, if the minimum stack is empty || value is less than the minimum stack top element, put the value stack, or re-entry once the top element

  Stack: If there are elements of the stack, then the stack

  Take the stack: the stack returns the data stack

  Takes the minimum value: returns the minimum stack Stack  

 

class Solution {

public:
    void push(int value) 
    {
        s_data.push(value);
        if((s_min.empty() == true) || (value < s_min.top()))
        {
            s_min.push(value);
        }
        else
        {
            s_min.push(s_min.top());
        }
    }
    void pop() 
    {
        if(s_data.top() > 0 && s_min.top() > 0)
        {
            s_min.pop();
            s_data.pop();
        }
    }
    int top() 
    {
        return s_data.top();
    }
    int min() 
    {
        return s_min.top();
    }
private:
    stack<int> s_data;
    stack<int> s_min;
};

  

 

 

 

Related topics:

  Minimum stack: achieve a minimum stack, there are three operations, min: minimum value obtained in the stack, Push: inserting an element in the stack, POP: pop the top element, that the time complexity of these actions are O ( 1)

  Get the maximum depth of n-dimensional array: input parameters for the n-dimensional array of type string, the value of each of the array of arrays or digital int. Please realize the maximum depth of a function, you can get a list of how many nested list.

  Forwarding postfix infix expression: infix expressions into postfix, enter a + b * c / d-a + f / b output abc * d / + a-fb / +

 

Guess you like

Origin www.cnblogs.com/xiexinbei0318/p/11432619.html