Leetcode[155] Min Stack
13 Nov 2015###Task1 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.
###Python
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.mstack = []
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
self.stack.append(x)
if len(self.mstack) == 0:
self.mstack.append(x)
else:
curmin = self.mstack[-1]
self.mstack.append(min(curmin, x))
def pop(self):
"""
:rtype: nothing
"""
self.stack.pop()
self.mstack.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.mstack[-1]
###Java ####One stack
class MinStack {
Stack<Long> stack = new Stack<Long>();
long min;
public void push(int x) {
if (stack.isEmpty()) {
stack.push(0L);
min = x;
} else {
stack.push(x - min);
min = x < min ? x : min;
}
}
public void pop() {
if (stack.isEmpty()) {
return;
}
long pop = stack.pop();
if (pop < 0) {
min = min - pop;
}
}
public int top() {
long top = stack.peek();
if (top > 0) {
return (int)(top + min);
}
return (int)min;
}
public int getMin() {
return (int)min;
}
}
####Two stacks
class MinStack {
private Stack<Integer> stack = new Stack<Integer>();
private Stack<Integer> minStack = new Stack<Integer>();
public void push(int x) {
stack.push(x);
if (!minStack.isEmpty()) {
int min = minStack.peek();
if (x < min) {
minStack.push(x);
} else {
minStack.push(min);
}
} else {
minStack.push(x);
}
}
public void pop() {
stack.pop();
minStack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}
###Points
- it is possible to use only single stack