原题
https://leetcode.cn/problems/min-stack/description/
思路
两个栈
复杂度
时间:O(n)
空间:O(n)
Python代码
class MinStack:
def __init__(self):
# 当前栈
self.stack1 = []
# 最小元素的栈
self.stack2 = []
def push(self, val: int) -> None:
self.stack1.append(val)
if len(self.stack2) == 0 or val < self.stack2[-1]:
self.stack2.append(val)
else:
self.stack2.append(self.stack2[-1])
def pop(self) -> None:
self.stack1.pop()
self.stack2.pop()
def top(self) -> int:
return self.stack1[-1]
def getMin(self) -> int:
return self.stack2[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
Go代码
type MinStack struct {
// 当前栈
stack1 []int
// 最小元素的栈
stack2 []int
}
func Constructor() MinStack {
return MinStack{}
}
func (this *MinStack) Push(val int) {
this.stack1 = append(this.stack1, val)
if len(this.stack2) == 0 || val < this.stack2[len(this.stack2)-1] {
this.stack2 = append(this.stack2, val)
} else {
this.stack2 = append(this.stack2, this.stack2[len(this.stack2)-1])
}
}
func (this *MinStack) Pop() {
this.stack1 = this.stack1[:len(this.stack1)-1]
this.stack2 = this.stack2[:len(this.stack2)-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]
}
/**
* Your MinStack object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(val);
* obj.Pop();
* param_3 := obj.Top();
* param_4 := obj.GetMin();
*/
882

被折叠的 条评论
为什么被折叠?



