main.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "strconv"
  7. "strings"
  8. )
  9. /*
  10. 1: push 5;push 2;push 1;push 3;push 0;min;top;pop;pop;pop;pop
  11. 2:
  12. */
  13. func main() {
  14. var minStack = Constructor()
  15. input := bufio.NewScanner(os.Stdin)
  16. for input.Scan() {
  17. line := input.Text()
  18. if strings.HasPrefix(line, "push ") {
  19. var digitStr = line[5:]
  20. var digit, _ = strconv.Atoi(digitStr)
  21. minStack.Push(digit)
  22. continue
  23. }
  24. if strings.HasPrefix(line, "pop") {
  25. minStack.Pop()
  26. }
  27. if strings.HasPrefix(line, "min") {
  28. fmt.Println(minStack.Min())
  29. }
  30. if strings.HasPrefix(line, "top") {
  31. fmt.Println(minStack.Top())
  32. }
  33. fmt.Println(minStack.Stack1, "--------", minStack.Stack2)
  34. }
  35. }
  36. type MinStack struct {
  37. Stack1 []int
  38. Stack2 []int
  39. }
  40. /** initialize your data structure here. */
  41. func Constructor() MinStack {
  42. return MinStack{}
  43. }
  44. func (this *MinStack) Push(x int) {
  45. this.Stack1 = append(this.Stack1, x)
  46. var length = len(this.Stack2)
  47. if length == 0 {
  48. this.Stack2 = append(this.Stack2, x)
  49. return
  50. }
  51. if this.Stack2[length-1] >= x {
  52. this.Stack2 = append(this.Stack2, x)
  53. }
  54. }
  55. func (this *MinStack) Pop() {
  56. var length = len(this.Stack1)
  57. if length == 0 {
  58. return
  59. }
  60. var value = this.Stack1[length-1]
  61. this.Stack1 = this.Stack1[0 : length-1]
  62. var stack2Length = len(this.Stack2)
  63. if this.Stack2[stack2Length-1] == value {
  64. this.Stack2 = this.Stack2[0 : stack2Length-1]
  65. }
  66. }
  67. func (this *MinStack) Top() int {
  68. var length = len(this.Stack1)
  69. if length == 0 {
  70. return -1
  71. }
  72. return this.Stack1[length-1]
  73. }
  74. func (this *MinStack) Min() int {
  75. var length = len(this.Stack2)
  76. if length == 0 {
  77. return -1
  78. }
  79. return this.Stack2[length-1]
  80. }