@@ -103,6 +103,10 @@ class Solution(object):
103103
104104- 每次入栈两个值:当前入栈元素、栈内最小值,保证栈内最小值永远在栈顶
105105
106+ <!-- tabs:start -->
107+
108+ #### ** Python**
109+
106110``` python
107111class MinStack (object ):
108112
@@ -153,6 +157,82 @@ class MinStack(object):
153157 return self .stack[len (self .stack) - 1 ]
154158```
155159
160+ #### ** Go**
161+
162+ ``` go
163+ type MinStack struct {
164+ Stack1 []int // 存放数据栈
165+ Stack2 []int // 递减栈
166+ }
167+
168+
169+ /* * initialize your data structure here. */
170+ func Constructor () MinStack {
171+ var minStack MinStack
172+ minStack.Stack1 = make ([]int , 0 )
173+ minStack.Stack2 = make ([]int , 0 )
174+ return minStack
175+ }
176+
177+
178+ func (this *MinStack ) Push (x int ) {
179+ // 入栈
180+ this.Stack1 = append (this.Stack1 , x)
181+ // 维护递减栈
182+ stack2Length := len (this.Stack2 )
183+ if stack2Length == 0 {
184+ this.Stack2 = append (this.Stack2 , x)
185+ } else {
186+ // 与栈顶元素对比
187+ top := this.Stack2 [stack2Length - 1 ]
188+ if x < top {
189+ this.Stack2 = append (this.Stack2 , x)
190+ } else {
191+ this.Stack2 = append (this.Stack2 , top)
192+ }
193+ }
194+ // fmt.Println(this.Stack1)
195+ // fmt.Println(this.Stack2)
196+ }
197+
198+
199+ func (this *MinStack ) Pop () {
200+ // 弹出元素
201+ stack1Length := len (this.Stack1 )
202+ this.Stack1 = this.Stack1 [:stack1Length - 1 ]
203+ stack2Length := len (this.Stack2 )
204+ this.Stack2 = this.Stack2 [:stack2Length - 1 ]
205+ // fmt.Println(this.Stack1)
206+ // fmt.Println(this.Stack2)
207+ }
208+
209+
210+ func (this *MinStack ) Top () int {
211+ // 返回栈顶元素
212+ stack1Length := len (this.Stack1 )
213+ return this.Stack1 [stack1Length - 1 ]
214+ }
215+
216+
217+ func (this *MinStack ) GetMin () int {
218+ // 返回 stack2 栈顶元素
219+ stack2Length := len (this.Stack2 )
220+ return this.Stack2 [stack2Length - 1 ]
221+ }
222+
223+
224+ /* *
225+ * Your MinStack object will be instantiated and called as such:
226+ * obj := Constructor();
227+ * obj.Push(x);
228+ * obj.Pop();
229+ * param_3 := obj.Top();
230+ * param_4 := obj.GetMin();
231+ */
232+ ```
233+
234+ <!-- tabs:end -->
235+
156236## 173. 二叉搜索树迭代器
157237
158238[ 原题链接] ( https://leetcode-cn.com/problems/binary-search-tree-iterator/ )
0 commit comments