Min Stack Solutions in Java
Number 155
Difficulty Easy
Acceptance 44.6%
Link LeetCode
Solutions
Java solution by haoel/leetcode
// Source : https://leetcode.com/problems/min-stack/description/// Author : Tianming Cao// Date : 2018-02-02package minStack;import java.util.Stack;public class MinStack {public Stack<Integer> mainStack;/*** Call an extra stack named assistStack to store the min value.* While we doing push operation, compare x with the top of assistStack and push the smaller value into assistStack.* The other operations pop,top and getMin is very simple.**/public Stack<Integer> assistStack;public MinStack() {mainStack = new Stack<Integer>();assistStack = new Stack<Integer>();}public void push(int x) {mainStack.push(x);if (assistStack.isEmpty()) {assistStack.push(x);} else {assistStack.push(Math.min(x, getMin()));}}public void pop() {mainStack.pop();assistStack.pop();}public int top() {return mainStack.peek();}public int getMin() {return assistStack.peek();}}