Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Stack<Integer> st = new Stack<Integer>(); Stack<Integer> stMin = new Stack<Integer>(); int min = 0; public void push(int x) { if (!st.isEmpty()) { if (min > x) { st.push(x); stMin.push(x); min = x; } else { st.push(x); stMin.push(min); } } else { st.push(x); stMin.push(x); min = x; } } public void pop() { st.pop(); stMin.pop(); if (!stMin.isEmpty())//元素出栈时要记着更新当前栈中的最小值 min = stMin.peek(); } public int top() { return st.peek(); } public int getMin() { return stMin.peek(); }
原文地址:http://blog.csdn.net/mnmlist/article/details/44875789