[Leetcode]最小栈

题目

 

代码

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack():nums(),sorted() 
    {
        
    }
    
    void push(int x) 
    {
        sorted[x]++;
        nums.push(x);
    }
    
    void pop() 
    {
        sorted[nums.top()]--;
        if(sorted[nums.top()]==0)
            sorted.erase(sorted.find(nums.top()));
        nums.pop();
    }
    
    int top() 
    {
        return nums.top();
    }
    
    int getMin() 
    {
        auto ptr= sorted.begin();
        return ptr->first;
    }
    std::map<int,int> sorted;
    std::stack<int> nums;
};

/**
 * 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();
 */
原文地址:https://www.cnblogs.com/lizhenghao126/p/11053567.html