private Stack<Integer> st; privateint minVal; /** initialize your data structure here. */ publicMinStack(){ st = new Stack<>(); minVal = Integer.MAX_VALUE; } publicvoidpush(int x){ if (x <= minVal){ st.push(minVal); minVal = x; } st.push(x); } publicvoidpop(){ if (minVal == st.pop()) minVal = st.pop(); } publicinttop(){ return st.peek(); } publicintgetMin(){ return minVal; } }
/** * 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(); */