1. 程式人生 > >155. Min Stack(python+cpp)

155. Min Stack(python+cpp)

題目:

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) – Push element x onto stack. pop() – Removes the element on top of the stack. top() – Get the top element. getMin() – Retrieve the minimum element in the stack. Example:

MinStack minStack = new MinStack(); 
minStack.push(-2); 
minStack.push(0); 
minStack.push(-3);
minStack.getMin();   --> Returns -3. 
minStack.pop(); 
minStack.top();   --> Returns 0. 
minStack.getMin();   --> Returns -2.

棧中的元素是個元組(x,curmin),curmin是當前最小值,每次push的時候更新curmin。 python程式碼:

class MinStack(object):

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

    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        curmin=
self.getMin() if curmin==None or curmin>x: curmin=x self._data.append((x,curmin)) def pop(self): """ :rtype: void """ self._data.pop()[0] def top(self): """ :rtype: int """ return self._data[
-1][0] def getMin(self): """ :rtype: int """ if self._data==[]: return None return self._data[-1][1] # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(x) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin()

c++程式碼:

#include<stack>
using namespace std;
class MinStack {
public:
    /** initialize your data structure here. */
    stack<vector<int>> data;
    MinStack() {
    }
    
    void push(int x) {
    
        int curmin=getMin();
        if(curmin==INT_MAX || curmin>x)
            curmin=x;
        vector<int> tmp={x,curmin};
        data.push(tmp);
        
    }
    
    void pop() {
        if(!data.empty())
            data.pop();
    }
    
    int top() {
        return data.top()[0];
    }
    
    int getMin() {
        if (data.empty())
            return INT_MAX;
        return data.top()[1];
    }
};

/**
 * 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();
 */

解釋: python 中可以x==None 但是c+中不行,所以如如果stack為空,令當前的最小值為INT_MAX總結: