155. 最小栈
最小栈
题目描述:
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
思路:
在编写的时候就把这个数到之前数的最小数append进去
代码:
type MinStack struct {
stack []int
minnum []int
}
func min(a, b int) int {
if a > b {
return b
} else {
return a
}
}
/** initialize your data structure here. */
func Constructor() MinStack {
return MinStack{
stack: []int{},
minnum: []int{math.},
}
}
func (this *MinStack) Push(val int) {
this.stack = append(this.stack, val)
this.minnum = append(this.minnum, min(this.minnum[len(this.minnum)-1],val))
}
func (this *MinStack) Pop() {
this.stack = append(this.stack[:len(this.stack)-1])
this.minnum = append(this.minnum[:len(this.minnum)-1])
}
func (this *MinStack) Top() int {
return this.stack[len(this.stack)-1]
}
func (this *MinStack) GetMin() int {
return this.minnum[len(this.minnum)-1]
}
代码效率:
执行用时:20 ms, 在所有 Go 提交中击败了86.09%的用户
内存消耗:8.3 MB, 在所有 Go 提交中击败了81.90%的用户
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!