问题
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) – 将元素 x 推入栈中。
pop() – 删除栈顶的元素。
top() – 获取栈顶元素。
getMin() – 检索栈中的最小元素
例子
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2
思路 方法1更容易记忆
首先使用一个栈,满足push,pop,top功能。
先添加该元素,再添加一个到该元素时,最小的元素
代码
//方法1
class MinStack {
int min = (1<<31)-1;
Stack<Integer> stack = new Stack<>();
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
if(x<min) min=x;
stack.push(min);
stack.push(x);
}
public void pop() {
stack.pop();
stack.pop();
min = stack.size()>0?stack.get(stack.size()-2):(1<<31)-1;
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
}
//方法2
class MinStack {
int min = (1<<31)-1;
Stack<Integer> stack = new Stack<>();
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
if (x<=min) {
stack.push(min);
min=x;
}
stack.push(x);
}
public void pop() {
if (stack.pop()==min) min = stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
}
#方法1
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.li = list()
self.min=(1<<31)-1
def push(self, x: int) -> None:
if x<self.min:self.min=x
self.li.append(self.min)
self.li.append(x)
def pop(self) -> None:
self.li.pop()
self.li.pop()
if len(self.li)>0:
self.min = self.li[-2]
else:
self.min = (1<<31)-1
def top(self) -> int:
return self.li[-1]
def getMin(self) -> int:
return self.min
//方法2
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.li=list()
self.min = (1<<31)-1
def push(self, x: int) -> None:
if x<=self.min:
self.li.append(self.min)
self.min=x
self.li.append(x)
def pop(self) -> None:
if self.li.pop()==self.min:
self.min=self.li.pop()
def top(self) -> int:
return self.li[-1]
def getMin(self) -> int:
return self.min