stack with min operation

Implement a stack with a min method that takes the minimum value. The min method will return the minimum value in the current stack.
The stack you implement will support push, pop and min operations, all of which require O(1) time.
Example The
following operations: push(1), pop() , push(2), push(3), min(), push(1), min() returns 1 , 2, 1

Note: The pop() function on lintcode also has a return value;

Ideas:

Store the smallest element of each time (the smaller value between the smallest element before the data stack and the newly pushed element) into the auxiliary stack. Ensure that the top of the auxiliary stack is always the smallest element of the data stack.
When the minimum element is popped from the data stack, and the top element of the auxiliary stack is popped at the same time, the new element at the top of the auxiliary stack is the next minimum value.
write picture description here

Code:

void push(int number) {
        // write your code here
        data_stack.push(number);
        if(min_stack.size()==0||number<min_stack.top())
            min_stack.push(number);
        else
            min_stack.push(min_stack.top());
    }

    /*
     * @return: An integer
     */
    int pop() {
        // write your code here
        assert(data_stack.size()>0&&min_stack.size()>0);
        min_stack.pop();
        int temp = data_stack.top();
        data_stack.pop();
        return temp;
    }

    /*
     * @return: An integer
     */
    int min() {
        // write your code here
        assert(data_stack.size()>0&&min_stack.size()>0);
        return min_stack.top();
    }
private:
    stack <int>data_stack;
    stack <int>min_stack;

Knowledge points:

The basic usage of c++ stack method:
push(): push a member into the stack;
pop(): pop a member from the top of the stack;
top(): return to the top of the stack, but do not delete the member;
size(): return to the stack The size of the inner element;
empty(): Returns true if the stack is empty, otherwise returns false;

assert(); terminates program execution if its condition returns an error

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325528698&siteId=291194637