본문 바로가기
개인 공부/코딩테스트

[C++][leetcode] Min Stack :: seoftware

by seowit 2020. 4. 12.

 


 

소스코드


 

class MinStack {
    stack<int> elements;
    stack<int> sorted;
public:
    /** initialize your data structure here. */
    MinStack() {
        
    }
    
    void push(int x) {
        elements.push(x);
        if(sorted.empty() || sorted.top() >= x) sorted.push(x);
    }
    
    void pop() {
        if(elements.empty()) return;
        if(sorted.top() == elements.top()) sorted.pop();
        elements.pop();
    }
    
    int top() {
        return elements.top();
    }
    
    int getMin() {
        return sorted.top();
    }
};

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

댓글