Loading

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

 

posted @ 2019-02-23 22:08  李正浩  阅读(103)  评论(0编辑  收藏  举报