标签:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Stack Data Structure
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; } };
标签:
原文地址:http://www.cnblogs.com/diegodu/p/4625615.html