Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
?
class MinStack { private Stack<Integer> m_data = new Stack<Integer>(); private Stack<Integer> m_min = new Stack<Integer>(); public void push(int x) { m_data.push(x); if (m_min.isEmpty() || x < m_min.peek()) { m_min.push(x); } else { m_min.push(m_min.peek()); } } public void pop() { // if (!m_min.isEmpty() && !m_data.isEmpty()) { m_min.pop(); m_data.pop(); // } } public int top() { return m_data.peek(); } public int getMin() { return m_min.peek(); } }
?
原文:http://hcx2013.iteye.com/blog/2219832