LeetCode155. 最小栈🌟🌟🌟🌟🌟中等
问题描述
原文链接:155. 最小栈
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
实现 MinStack 类:
MinStack()初始化堆栈对象。void push(int val)将元素val推入堆栈。void pop()删除堆栈顶部的元素。int top()获取堆栈顶部的元素。int getMin()获取堆栈中的最小元素。
示例 1:
输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
输出:
[null,null,null,null,-3,null,0,-2]
解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
提示:
-231 <= val <= 231 - 1pop、top和getMin操作总是在非空栈上调用push,pop,top, andgetMin最多被调用3 * 104次
代码实现
Java
class MinStack {
Stack<Integer> stack1;
Stack<Integer> stack2;
public MinStack() {
stack1 = new Stack();
stack2 = new Stack();
}
public void push(int val) {
stack1.push(val);
if(stack2.isEmpty() || stack2.peek() >= val){
stack2.push(val);
}
}
public void pop() {
if(stack1.peek().intValue() == stack2.peek().intValue()){
stack2.pop();
}
stack1.pop();
}
public int top() {
return stack1.peek();
}
public int getMin() {
return stack2.peek();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
Python
class MinStack(object):
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, val):
"""
:type val: int
:rtype: None
"""
self.stack1.append(val)
if not self.stack2 or self.stack2[-1] >= val:
self.stack2.append(val)
def pop(self):
"""
:rtype: None
"""
if self.stack1[-1] == self.stack2[-1]:
self.stack2.pop()
self.stack1.pop()
def top(self):
"""
:rtype: int
"""
return self.stack1[-1]
def getMin(self):
"""
:rtype: int
"""
return self.stack2[-1]
C++
class MinStack {
public:
stack<int> stack1;
stack<int> stack2;
MinStack() {
}
void push(int val) {
stack1.push(val);
if(stack2.empty() || stack2.top() >= val){
stack2.push(val);
}
}
void pop() {
if(stack1.top() == stack2.top()){
stack2.pop();
}
stack1.pop();
}
int top() {
return stack1.top();
}
int getMin() {
return stack2.top();
}
};
Go
type MinStack struct {
stack1 []int
stack2 []int
}
func Constructor() MinStack {
return MinStack{[]int{}, []int{}}
}
func (this *MinStack) Push(val int) {
this.stack1 = append(this.stack1, val)
if len(this.stack2) == 0 || this.stack2[len(this.stack2)-1] >= val {
this.stack2 = append(this.stack2, val)
}
}
func (this *MinStack) Pop() {
if this.stack1[len(this.stack1)-1] == this.stack2[len(this.stack2)-1] {
this.stack2 = this.stack2[:len(this.stack2)-1]
}
this.stack1 = this.stack1[:len(this.stack1)-1]
}
func (this *MinStack) Top() int {
return this.stack1[len(this.stack1)-1]
}
func (this *MinStack) GetMin() int {
return this.stack2[len(this.stack2)-1]
}
评论(6)
打卡st; min_st;
class MinStack {
private:
stack
stack
public:
//辅助栈存放不同时期栈中的最小值
//找最小值,用INT32_MAX初始化
MinStack() {
min_st.push(INT32_MAX);
}
};
打卡