classMinStack{ private Stack<Integer> stack = new Stack<>(); private Stack<Integer> buffer = new Stack<>(); privateint min = Integer.MAX_VALUE;
publicvoidpush(int x){ stack.push(x); if (x < min) { min = x; } }
// takes O(N) time publicvoidpop(){ // assume not empty int val = stack.pop(); if (val == min) { // update min (find the new min) int newMin = Integer.MAX_VALUE; // consider size = 1, min should be reset // put aside while (stack.size() > 0) { int x = stack.pop(); newMin = Math.min(newMin, x); buffer.push(x); } min = newMin; // put it back while (temp.size() > 0) { stack.push(temp.pop()); } } }
publicinttop(){ // assume not empty return stack.peek(); }