Skip to content

Commit 2b7f471

Browse files
committed
栈: 最小栈
Change-Id: Ia2f0b8ca7d9fa61cc1b1d55e513059b675e22ab3
1 parent 58295d6 commit 2b7f471

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed

go/leetcode/155.最小栈.go

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
/*
2+
* @lc app=leetcode.cn id=155 lang=golang
3+
*
4+
* [155] 最小栈
5+
*
6+
* https://leetcode-cn.com/problems/min-stack/description/
7+
*
8+
* algorithms
9+
* Easy (49.91%)
10+
* Likes: 285
11+
* Dislikes: 0
12+
* Total Accepted: 45.8K
13+
* Total Submissions: 91.3K
14+
* Testcase Example: '["MinStack","push","push","push","getMin","pop","top","getMin"]\n[[],[-2],[0],[-3],[],[],[],[]]'
15+
*
16+
* 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
17+
*
18+
*
19+
* push(x) -- 将元素 x 推入栈中。
20+
* pop() -- 删除栈顶的元素。
21+
* top() -- 获取栈顶元素。
22+
* getMin() -- 检索栈中的最小元素。
23+
*
24+
*
25+
* 示例:
26+
*
27+
* MinStack minStack = new MinStack();
28+
* minStack.push(-2);
29+
* minStack.push(0);
30+
* minStack.push(-3);
31+
* minStack.getMin(); --> 返回 -3.
32+
* minStack.pop();
33+
* minStack.top(); --> 返回 0.
34+
* minStack.getMin(); --> 返回 -2.
35+
*
36+
*
37+
*/
38+
39+
// 最小值也是一个栈,每次发现有更小的值就加入栈,出栈的时候检查是否最小值,是的话从min栈里出去
40+
type MinStack struct {
41+
Data []int
42+
min []int
43+
}
44+
45+
46+
/** initialize your data structure here. */
47+
func Constructor() MinStack {
48+
return MinStack{
49+
Data: []int{},
50+
min: []int{},
51+
}
52+
}
53+
54+
55+
func (this *MinStack) Push(x int) {
56+
this.Data = append(this.Data, x) // 2 0 3
57+
if len(this.min) <= 0 || this.min[len(this.min)-1] >= x { // NOTE: 注意=也要加进去
58+
this.min = append(this.min, x) // 2 0
59+
}
60+
}
61+
62+
63+
func (this *MinStack) Pop() {
64+
if len(this.Data) <= 0 {
65+
return
66+
}
67+
v := this.Data[len(this.Data)-1] // 3 0 2
68+
this.Data = this.Data[:len(this.Data)-1]
69+
if len(this.min) > 0 && v <= this.min[len(this.min)-1] {
70+
this.min = this.min[:len(this.min)-1] // 2 0
71+
}
72+
}
73+
74+
75+
func (this *MinStack) Top() int {
76+
if len(this.Data) <= 0 {
77+
return 0
78+
}
79+
return this.Data[len(this.Data)-1]
80+
}
81+
82+
83+
func (this *MinStack) GetMin() int {
84+
if len(this.min) <= 0 {
85+
return 0
86+
}
87+
return this.min[len(this.min)-1]
88+
}
89+
90+
91+
/**
92+
* Your MinStack object will be instantiated and called as such:
93+
* obj := Constructor();
94+
* obj.Push(x);
95+
* obj.Pop();
96+
* param_3 := obj.Top();
97+
* param_4 := obj.GetMin();
98+
*/
99+

0 commit comments

Comments
 (0)