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.
class MinStack { private: vector<int> m_data; vector<int> m_min; public: void push(int x) { if(m_data.size() == 0) m_min.push_back(x); else { if(m_min[m_min.size() - 1] > x) m_min.push_back(x); else m_min.push_back(m_min[m_min.size() - 1]); } m_data.push_back(x); } void pop() { m_data.pop_back(); m_min.pop_back(); } int top() { int size = m_data.size(); if(size > 0) return m_data[size - 1]; else return -1; } int getMin() { int size = m_min.size(); if(size > 0) return m_min[size - 1]; else return -1; } };