LeetCode -- Min Stack
Question: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Push (x) -- Push element x onto stack.
Pop () -- Removes the element on top of the stack.
Top () -- Get the top element.
GetMin () -- Retrieve the minimum element in the stack.
Solution 1:
class MinStack { private Stack
mStack = new Stack
();private Stack
mMinStack = new Stack
();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();}}
Ps: solution 1's doubts when I first saw this solution, I always felt strange. It was a problem, especially the two sentences of the push method int min = mMinStack. peek ();
If (x <= min ){
MMinStack. push (x );
} Then I gave me the answer to this question in a blog post. Analysis in blog:
The key to this question lies in the design of minStack, And the built-in Java Stack of the push () pop () top () operations. Needless to say. I first thought about getting two more arrays, respectively recording the first one of each element that is bigger than it and the last one that is smaller than it, and thought it was complicated. The first time I read the above code, I still think it is wrong.
Solution 2 (efficient and easy to understand ):
class MinStack { Node top = null; public void push(int x) { if (top == null) { top = new Node(x); top.min = x; } else { Node temp = new Node(x); temp.next = top; top = temp; top.min = Math.min(top.next.min, x); } } public void pop() { top = top.next; return; } public int top() { return top == null ? 0 : top.val; } public int getMin() { return top == null ? 0 : top.min; }}class Node { int val; int min; Node next; public Node(int val) { this.val = val; }}