Featured image of post 剑指 Offer 30. 包含 min 函数的栈

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

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O (1)。

示例:

1
2
3
4
5
6
7
8
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.min();   --> 返回 -2.

提示: 各函数的调用总次数不超过 20000 次

解法一:模拟

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
type MinStack struct {
    stack []int
    min int
}

/** initialize your data structure here. */
func Constructor() MinStack {
    return MinStack{}
}


func (this *MinStack) Push(x int) {
    if len(this.stack) == 0 {
        this.stack = append(this.stack, 0)
        this.min = x
    } else {
        this.stack = append(this.stack, x-this.min)
        if this.min > x {
            this.min = x
        }
    }
}

func (this *MinStack) Pop() {
    n := len(this.stack)-1
    if n < 0 {
        panic("no value to popup!")
    }
    if this.stack[n] < 0 {
        this.min = this.min - this.stack[n]
    }
    this.stack = this.stack[:n]
}

func (this *MinStack) Top() int {
    n := len(this.stack)-1
    // 注意:不能直接返回 this.stack[n] + this.min
    if this.stack[n] > 0 {
        return this.stack[n] + this.min
    } else {
        return this.min
    }
}

func (this *MinStack) Min() int {
    return this.min
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2023/06/14 23:25:10
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计