列表

详情


剑指 Offer 30. 包含min函数的栈

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 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.

 

提示:

  1. 各函数的调用总次数不超过 20000 次

 

注意:本题与主站 155 题相同:https://leetcode.cn/problems/min-stack/

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class MinStack { public: /** initialize your data structure here. */ MinStack() { } void push(int x) { } void pop() { } int top() { } int min() { } }; /** * Your MinStack object will be instantiated and called as such: * MinStack* obj = new MinStack(); * obj->push(x); * obj->pop(); * int param_3 = obj->top(); * int param_4 = obj->min(); */

golang 解法, 执行用时: 60 ms, 内存消耗: 8.2 MB, 提交时间: 2020-11-09 23:25:14

type MinStack struct {
    stack []int
    length int
}


/** initialize your data structure here. */
func Constructor() MinStack {
    return MinStack{stack: []int{}, length: 0}
}


func (this *MinStack) Push(x int)  {
    this.length += 1
    this.stack = append(this.stack, x)
}


func (this *MinStack) Pop()  {
    this.length -= 1
    this.stack = this.stack[:this.length]
}


func (this *MinStack) Top() int {
    return this.stack[this.length-1]
}


func (this *MinStack) Min() int {
    min := this.stack[0]
    for i := 1; i < this.length; i++ {
        if min > this.stack[i] {
            min = this.stack[i]
        }
    }
    return min
}


/**
 * 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();
 */

python3 解法, 执行用时: 560 ms, 内存消耗: 16.6 MB, 提交时间: 2020-11-09 23:12:54

class MinStack:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []


    def push(self, x: int) -> None:
        self.stack.append(x)

    def pop(self) -> None:
        self.stack.pop()

    def top(self) -> int:
        return self.stack[-1]

    def min(self) -> int:
        return min(self.stack)



# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.min()

上一题