Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8f54727

Browse files
committed
Add: Min Stack
1 parent 2eac959 commit 8f54727

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

‎problems/min-stack/min_stack.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,39 @@
11
package min_stack
2+
3+
type MinStack struct {
4+
stack [][2]int
5+
}
6+
7+
/** initialize your data structure here. */
8+
func Constructor() MinStack {
9+
return MinStack{}
10+
}
11+
12+
func (this *MinStack) Push(x int) {
13+
min, l := x, len(this.stack)
14+
if l > 0 && this.stack[l-1][1] < x {
15+
min = this.stack[l-1][1]
16+
}
17+
this.stack = append(this.stack, [2]int{x, min})
18+
}
19+
20+
func (this *MinStack) Pop() {
21+
this.stack = this.stack[:len(this.stack)-1]
22+
}
23+
24+
func (this *MinStack) Top() int {
25+
return this.stack[len(this.stack)-1][0]
26+
}
27+
28+
func (this *MinStack) GetMin() int {
29+
return this.stack[len(this.stack)-1][1]
30+
}
31+
32+
/**
33+
* Your MinStack object will be instantiated and called as such:
34+
* obj := Constructor();
35+
* obj.Push(x);
36+
* obj.Pop();
37+
* param_3 := obj.Top();
38+
* param_4 := obj.GetMin();
39+
*/

‎problems/min-stack/min_stack_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,33 @@
11
package min_stack
2+
3+
import (
4+
"reflect"
5+
"testing"
6+
)
7+
8+
type caseType struct {
9+
input []int
10+
expected []int
11+
}
12+
13+
func TestConstructor(t *testing.T) {
14+
tests := [...]caseType{
15+
{
16+
input: []int{-2, 0, -3},
17+
expected: []int{-3, 0, -2},
18+
},
19+
}
20+
for _, tc := range tests {
21+
minStack, output := Constructor(), make([]int, 0)
22+
for _, x := range tc.input {
23+
minStack.Push(x)
24+
}
25+
output = append(output, minStack.GetMin())
26+
minStack.Pop()
27+
output = append(output, minStack.Top())
28+
output = append(output, minStack.GetMin())
29+
if !reflect.DeepEqual(output, tc.expected) {
30+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
31+
}
32+
}
33+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /