思路:使用辅助栈存取最小元素
class MinStack:
def __init__(self):
self.data = []
self.helper = []
def push(self, x):
self.data.append(x)
if len(self.helper) == 0 or x <= self.helper[-1]:
self.helper.append(x)
else:
self.helper.append(self.helper[-1])
def pop(self):
if self.data:
self.helper.pop()
return self.data.pop()
def top(self):
if self.data:
return self.data[-1]
def getMin(self):
if self.helper:
return self.helper[-1]
public class MinStack {
public Stack<int> x_stack = new Stack<int>();
public Stack<int> min_stack = new Stack<int>();
/** initialize your data structure here. */
public MinStack()
{
min_stack.Push(int.MaxValue);
}
public void Push(int x)
{
x_stack.Push(x);
//if(min_stack.Count == 0 || min_stack.Peek() > x)
//{
//min_stack.Push(x);
//}
min_stack.Push(Math.Min(min_stack.Peek(), x));
}
public void Pop()
{
//if(min_stack.Peek() == x_stack.Peek())
//{
//min_stack.Pop();
//}
x_stack.Pop();
min_stack.Pop();
}
public int Top()
{
return x_stack.Peek();
}
public int GetMin()
{
return min_stack.Peek();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.Push(x);
* obj.Pop();
* int param_3 = obj.Top();
* int param_4 = obj.GetMin();
*/