doudang4857 2014-12-15 02:30
浏览 28
已采纳

没有内置的动态数组吗?

I have just started to pick up go, and I was going over the data structures. I am used to having a dynamic array like list in python or std::vector in C++, but I don't see anything similar in go. The nice things about dynamic array is that it has O(1) time complexity to add a new element, and O(1) time complexity for indexing.

First I thought that slice is it, but then I realized that when I used append function, the whole slice is being copied, and then therefore it is an O(N) operations as opposed to O(1) in dynamic array.

Then I came across list but this is a doubly linked list, which means that indexing is O(N), as opposed to O(1).

Am I missing the data structure I am looking for?

  • 写回答

1条回答 默认 最新

  • dongre6270 2014-12-15 02:47
    关注

    First I thought that slice is it, but the[n] I realized that when I used append function, the whole slice is being copied, and then therefore it is an O(N) operations as opposed to O(1) in dynamic array.

    This is not correct.

    Per The Go Programming Language Specification, append examines the capacity of the array that backs the slice, and only allocates new memory (copying the slice) if there's not enough room in the backing array. [link] I don't see anything in the specification proper that specifies how much memory it should allocate, but according to the blog post you link to, the new block of memory will be 1.5 times the current size of the slice. That means that, after a reallocating/copying insertion, the next n/2 insertions will not require reallocating/copying. The overall effect is amortized O(1) time. This is the same approach used by the examples you mention in other languages (list in Python, std::vector in C++).

    So, slices are exactly what you need.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求直线方程 使平面上n个点在直线同侧并且距离总和最小
  • ¥50 java算法,给定试题的难度数量(简单,普通,困难),和试题类型数量(单选,多选,判断),以及题库中各种类型的题有多少道,求能否随机抽题。
  • ¥50 rk3588板端推理
  • ¥250 opencv怎么去掉 数字0中间的斜杠。
  • ¥15 这种情况的伯德图和奈奎斯特曲线怎么分析?
  • ¥250 paddleocr带斜线的0很容易识别成9
  • ¥15 电子档案元素采集(tiff及PDF扫描图片)
  • ¥15 flink-sql-connector-rabbitmq使用
  • ¥15 zynq7015,PCIE读写延时偏大
  • ¥15 使用spss做psm(倾向性评分匹配)遇到问题