最小栈
題目:
設(shè)計一個支持 push,pop,top 操作,并能在常數(shù)時間內(nèi)檢索到最小元素的棧。push(x) – 將元素 x 推入棧中。
pop() – 刪除棧頂?shù)脑亍?br /> 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
解題思路:輔助棧
除了用一個存值棧存放值,我們還需要一個輔助棧。這個輔助棧的棧頂總是存儲存值棧中的最小元素對應(yīng)的值,兩個棧同時push和pop,這樣獲取最小值時就是O(1)時間度復(fù)度。
type MinStack struct {stack []intminStack []int }//最小棧構(gòu)造函數(shù) func Constructor() MinStack {return MinStack{stack: []int{}, //棧minStack: []int{math.MaxInt64}, //輔助棧} }//入棧 func (this *MinStack) Push(x int) {this.stack = append(this.stack, x)//取出輔助棧的toptop := this.minStack[len(this.minStack)-1]this.minStack = append(this.minStack, min(x, top)) }//出棧 func (this *MinStack) Pop() {this.stack = this.stack[:len(this.stack)-1]this.minStack = this.minStack[:len(this.minStack)-1] }//獲取棧頂元素 func (this *MinStack) Top() int {return this.stack[len(this.stack)-1] }//獲取最小值 func (this *MinStack) GetMin() int {return this.minStack[len(this.minStack)-1] }func min(x, y int) int {if x < y {return x}return y }?
?
參考地址:https://leetcode-cn.com/problems/min-stack/solution/zui-xiao-zhan-by-leetcode-solution/
總結(jié)
- 上一篇: 动态规划经典例题:乘积最大连续子数组
- 下一篇: 表分区优点