Stack with min operation - LintCode

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.

 注意事项
如果堆栈中没有数字则不能进行min方法的调用

Example The
following operations: push(1), pop(), push(2), push(3), min(), push(1), min() returns 1, 2, 1

Ideas
Use stacks stack1 and stack2, and stack2 stores the minimum value. When num is pushed into the stack, it is directly pushed into stack1. If stack2 is empty, it is directly pushed into the stack. Otherwise, the top of stack2 and the smaller value of num are pushed into the stack. When popping, stack1 and stack2 are popped at the same time. The min operation directly returns the top element of stack2.

#ifndef C_12_H
#define C_12_H
#include<iostream>
#include<stack>
using namespace std;
class MinStack {
public:
    MinStack() {
        // do intialization if necessary
    }

    /*
    * @param number: An integer
    * @return: nothing
    */
    void push(int number) {
        // write your code here
        //当stack2为空,直接压栈
        //否则将取栈顶和number的最大值,压栈
        stack1.push(number);
        if (stack2.empty())
            stack2.push(number);
        else
        {
            int minVal = stack2.top();
            minVal = minVal < number ? minVal : number;
            stack2.push(minVal);
        }
    }

    /*
    * @return: An integer
    */
    int pop() {
        // write your code here
        //stack1,stack2同时出栈
        int res = 0;
        if (!stack1.empty() && !stack2.empty())
        {
            res = stack1.top();
            stack1.pop();
            stack2.pop();
        }
        return res;
    }

    /*
    * @return: An integer
    */
    int min() {
        // write your code here
        //直接取stack2的栈顶
        if (!stack2.empty())
            return stack2.top();
    }
    stack<int> stack1, stack2;//stack1为主栈,stack2为辅助栈存放最小值
};
#endif

Guess you like

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