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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| package main
import ( "fmt" "strconv" )
type MinStack struct { stack []int mins []int }
func Constructor() MinStack { return MinStack{ stack: []int{}, mins: []int{}, } }
func (this *MinStack) Push(val int) { this.stack = append(this.stack, val) if len(this.mins) == 0 || val <= this.mins[len(this.mins)-1] { this.mins = append(this.mins, val) } }
func (this *MinStack) Pop() { if len(this.stack) > 0 { if this.stack[len(this.stack)-1] == this.mins[len(this.mins)-1] { this.mins = this.mins[:len(this.mins)-1] } this.stack = this.stack[:len(this.stack)-1] } }
func (this *MinStack) Top() int { if len(this.stack) > 0 { return this.stack[len(this.stack)-1] } return -1 }
func (this *MinStack) GetMin() int { if len(this.mins) > 0 { return this.mins[len(this.mins)-1] } return -1 }
func main() { testCases := []struct { commands [][]string expected []string }{ { commands: [][]string{ {"MinStack", "push", "push", "push", "getMin", "pop", "top", "getMin"}, {"", "-2", "0", "-3", "", "", "", ""}, }, expected: []string{"null", "null", "null", "null", "-3", "null", "0", "-2"}, }, } for i, tc := range testCases { fmt.Printf("Test Case %d:\n", i+1) minStack := Constructor() outputs := []string{}
for j := 0; j < len(tc.commands[0]); j++ { cmd := tc.commands[0][j] args := tc.commands[1][j]
switch cmd { case "MinStack": outputs = append(outputs, "null") case "push": val, _ := strconv.Atoi(args) minStack.Push(val) outputs = append(outputs, "null") case "pop": minStack.Pop() outputs = append(outputs, "null") case "top": outputs = append(outputs, strconv.Itoa(minStack.Top())) case "getMin": outputs = append(outputs, strconv.Itoa(minStack.GetMin())) } } fmt.Printf("Input: commands = %v\n", tc.commands) outputsStr := fmt.Sprint(outputs) expectedStr := fmt.Sprint(tc.expected)
if outputsStr == expectedStr { fmt.Printf("Output: %v, PASS\n", outputsStr) } else { fmt.Printf("Output: %v, FAIL (Expected: %v)\n", outputsStr, expectedStr) } } }
|