Java solution (accepted)


  • 26
    P
    private Stack<Integer> mStack = new Stack<Integer>();
    private Stack<Integer> mMinStack = new Stack<Integer>();
    
    public void push(int x) {
    	mStack.push(x);
    	if (mMinStack.size() != 0) {
    		int min = mMinStack.peek();
    		if (x <= min) {
    			mMinStack.push(x);
    		}
    	} else {
    		mMinStack.push(x);
    	}
    }
    
    public void pop() {
    	int x = mStack.pop();
    	if (mMinStack.size() != 0) {
    		if (x == mMinStack.peek()) {
    			mMinStack.pop();
    		}
    	}
    }
    
    public int top() {
    	return mStack.peek();
    }
    
    public int getMin() {
        return mMinStack.peek();
    }

  • 7
    E

    This might be shorter

    class MinStack {
        Stack<Integer> min = new Stack<>();
        Stack<Integer> stack = new Stack<>();
        public void push(int x) {
            stack.push(x);
            if (min.isEmpty() || min.peek() >= x) {
                min.push(x);
            }
        }
    
        public void pop() {
            if (stack.pop().equals(min.peek())) {
                min.pop();
            }
        }
    
        public int top() {
            return stack.peek();
        }
    
        public int getMin() {
            return min.peek();
        }
    }
    

  • 0
    Z

    great! same idea with you but one thing i wonder is if i changed (stack.pop().equals(min.peek())) to if(stack.pop() == min.peek()) i would get wrong answer, do you know why its happened?


  • 1
    M

    You are comparing two Integer objects if using "==" and the two will only be the same if they are the same objects(stored in same address), but what you want to compare is actually the value of the two objects, so use ("equals").


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.