1. 程式人生 > >leetcode 155 Min Stack

leetcode 155 Min Stack

python:

class MinStack:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []
        

    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        self.stack.append(x)

    def pop(self):
        """
        :rtype: void
        """
        del self.stack[-1]
        

    def top(self):
        """
        :rtype: int
        """
        return self.stack[-1]

    def getMin(self):
        """
        :rtype: int
        """
        return min(self.stack)

c++:

class MinStack {
private:
    vector<int> stack;
    int minn;
public:
    /** initialize your data structure here. */
    MinStack() {
        
    }
    
    void push(int x) {
        if(stack.empty()) minn=x;
        else minn = min(x, minn);
        stack.push_back(x);
    }
    
    void pop() {
        stack.pop_back();
        if(stack.empty())
            minn = NULL;
        else{
            minn = stack[0];
            for (auto s:stack){
                minn = min(s, minn);
            }
        }
    }
    
    int top() {
        return stack.back();
    }
    
    int getMin() {
        return minn;
    }
};