定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
提示:
注意:本题与主站 155 题相同:https://leetcode-cn.com/problems/min-stack/
golang
普通栈的 push() 和 pop() 函数的复杂度为 O(1) ;而获取栈最小值 min() 函数需要遍历整个栈,复杂度为O(N)。
本题难点
: 将 min() 函数复杂度降为 O(1),可通过建立辅助栈实现;
数据栈 A: 栈 A 用于存储所有元素,保证入栈 push() 函数、出栈 pop() 函数、获取栈顶 top() 函数的正常辑。
辅助栈 B: 栈 B 中存储栈 A 中所有 非严格降序 的元素,则栈 A 中的最小元素始终对应栈 B 的栈顶元素,即 min() 函数只需返回栈 B 的栈顶元素即可。
因此,只需设法维护好 栈 B 的元素,使其保持非严格降序
,即可实现 min() 函数的 O(1) 复杂度。
/*
一个栈正常的push,pop,top操作的时间复杂度都为O(1)
难点在于将min的时间复杂度从O(n)降低到O(1)
定义两个栈:stackA用于正常的栈操作
而stackB作为辅助栈用于存放stackA中非递增的值
*/
type MinStack struct {
stackA []int
stackB []int
}
/** initialize your data structure here. */
func Constructor() MinStack {
return MinStack{
stackA: []int{},
stackB: []int{},
}
}
/*
对于stackA,就是正常向栈中追加元素
对于stackB,只有当stackB为空 || 当前元素小于stackB的栈顶元素时再进行追加
*/
func (this *MinStack) Push(x int) {
this.stackA = append(this.stackA, x)
if len(this.stackB) == 0 || x <= this.stackB[len(this.stackB)-1] {
this.stackB = append(this.stackB, x)
}
}
/*
对于stackA,就是正常的出栈操作
对于stackB,只有当stackB栈的栈顶元素==stackA栈的栈顶元素时才出栈
*/
func (this *MinStack) Pop() {
top := this.Top()
this.stackA = this.stackA[:len(this.stackA)-1]
if top == this.stackB[len(this.stackB)-1] {
this.stackB = this.stackB[:len(this.stackB)-1]
}
}
// 直接返回stackA的栈顶元素即可
func (this *MinStack) Top() int {
return this.stackA[len(this.stackA)-1]
}
// 直接返回stackB的栈顶元素即可
func (this *MinStack) Min() int {
return this.stackB[len(this.stackB)-1]
}
/**
* Your MinStack object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* obj.Pop();
* param_3 := obj.Top();
* param_4 := obj.Min();
*/
原文:https://www.cnblogs.com/zmk-c/p/14793160.html