首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >golang刷leetcode 技巧(26)堆盘子

golang刷leetcode 技巧(26)堆盘子

作者头像
golangLeetcode
发布2022-08-02 18:43:37
发布2022-08-02 18:43:37
3290
举报

堆盘子。设想有一堆盘子,堆太高可能会倒下来。因此,在现实生活中,盘子堆到一定高度时,我们就会另外堆一堆盘子。请实现数据结构SetOfStacks,模拟这种行为。SetOfStacks应该由多个栈组成,并且在前一个栈填满时新建一个栈。此外,SetOfStacks.push()和SetOfStacks.pop()应该与普通栈的操作方法相同(也就是说,pop()返回的值,应该跟只有一个栈时的情况一样)。进阶:实现一个popAt(int index)方法,根据指定的子栈,执行pop操作。

当某个栈为空时,应当删除该栈。当栈中没有元素或不存在该栈时,pop,popAt 应返回 -1.

示例1:

输入:

["StackOfPlates", "push", "push", "popAt", "pop", "pop"]

[[1], [1], [2], [1], [], []]

输出:

[null, null, null, 2, 1, -1]

示例2:

输入:

["StackOfPlates", "push", "push", "push", "popAt", "popAt", "popAt"]

[[2], [1], [2], [3], [0], [0], [0]]

输出:

[null, null, null, null, 2, 1, 3]

解题思路

1,这里并不复杂,只是将一个栈换成了多个栈

2,需要注意的是输入cap为0的情况需要特殊处理

3,如果当前栈最后一个元素出栈,需要删除栈

4,如果上一个栈满了,需要新建一个栈

代码实现

代码语言:javascript
复制
type StackOfPlates struct {
  cap int
  data [][]int
}


func Constructor(cap int) StackOfPlates {
    return StackOfPlates{cap:cap}
}


func (this *StackOfPlates) Push(val int)  {
    if this.cap==0{
        return
    }
    i:=len(this.data)
    if i==0 || len(this.data[i-1])==this.cap{
       this.data=append(this.data,[]int{val})
    }else{
       this.data[i-1]=append(this.data[i-1],val)
    }
}


func (this *StackOfPlates) Pop() int {
   l:= len(this.data)
   if l==0{
       return -1
   }
   l1:=len(this.data[l-1])
   val:=this.data[l-1][l1-1]
   if l1==1{
       this.data=this.data[:l-1:l-1]
   }else{
       this.data[l-1]=this.data[l-1][:l1-1:l1-1]
   }
   return val
}


func (this *StackOfPlates) PopAt(index int) int {
   l:=len(this.data)
   if index>l-1{
       return -1
   } 
   l1:=len(this.data[index])
   val:=this.data[index][l1-1]
   if l1==1{
       this.data=append(this.data[:index:index],this.data[index+1:]...)
   }else{
       this.data[index]=this.data[index][:l1-1:l1-1]
   }
   return val
}


/**
 * Your StackOfPlates object will be instantiated and called as such:
 * obj := Constructor(cap);
 * obj.Push(val);
 * param_2 := obj.Pop();
 * param_3 := obj.PopAt(index);
 */
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-03-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 golang算法架构leetcode技术php 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档