代码随想录算法训练营第9天 | lc232、lc225

发布时间 2023-12-10 02:27:16作者: geJoyo

(本合集全部为Go语言实现)

相关文章链接:232题解 225题解
相关视频链接:

Leetcode232

状态:在go语音对于队列和栈的实现上稍微卡了一下
实现过程中的难点:对于进队和出队两块的思路想出来就好写了

个人写法

type MyQueue struct {
  inStack, outStack []int
}


func Constructor() MyQueue {
  return MyQueue{}
}

func (this *MyQueue) Push(x int)  {
  this.inStack = append(this.inStack, x)
}

func (this *MyQueue) in2out() {
  for i := len(this.inStack) - 1; i >= 0; i-- {
    this.outStack = append(this.outStack, this.inStack[i])
  }
  this.inStack = this.inStack[:0]
}

func (this *MyQueue) Pop() int {
  if len(this.outStack) == 0 {
    this.in2out()
  }
  res := this.outStack[len(this.outStack) - 1]
  this.outStack = this.outStack[:len(this.outStack) - 1]
  return res
}

func (this *MyQueue) Peek() int {
  if len(this.outStack) == 0 {
    this.in2out()
  }
  return this.outStack[len(this.outStack) - 1]
}

func (this *MyQueue) Empty() bool {
  return len(this.inStack) == 0 && len(this.outStack) == 0
}

Leetcode225

状态:因为go的切片的理解问题,卡了一下
实现过程中的难点:着重理解压栈和弹栈两块的实现

个人写法

type MyStack struct {
 pushQueue, popQueue []int
}

func Constructor() MyStack {
  return MyStack{}
}

func (this *MyStack) Push(x int)  {
  this.pushQueue = append(this.pushQueue, x)
  for _, item := range this.popQueue {
    this.pushQueue = append(this.pushQueue, item)
  }
  this.pushQueue, this.popQueue = this.popQueue[:0], this.pushQueue
}

func (this *MyStack) Pop() int {
  res := this.popQueue[0]
  this.popQueue = this.popQueue[1:]
  return res
}

func (this *MyStack) Top() int {
  return this.popQueue[0]
}

func (this *MyStack) Empty() bool {
  return len(this.popQueue) == 0
}

今日收获

  • 对go的切片有了更好的理解,确实很灵活

学习时长:1.5小时左右