Is splicing slices in go O(1)?

xuanbao · · 455 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Would <code>tmp = append(tmp[0:i], tmp[i+1:]...)</code> would be an O(1) operation? I was told this on chat and it kinda blew my mind.</p> <p>Is a similar operation such as <code>tmp = tmp[1:]</code> O(1)? (basically treating <code>tmp</code> like a queue. I&#39;m assuming any slicing is O(1)? </p> <hr/>**评论:**<br/><br/>jackmott2: <pre><p><code>tmp = tmp[1:]</code> is definitely O(1) its just changing a pointer.</p> <p>append though, might be log(n) amortized?</p> <p>edit: nope, amortized is O(1), worst case is O(n)</p> <p>remember that append will occasionally have to make a new, bigger array and copy elements from the old into the new.</p></pre>UpOnCloud9: <pre><p>I realized I wrote it out wrong last night. It&#39;s O(1) even with the spread operator? <code>tmp = append(tmp[0:i], tmp[i+1:]...)</code></p></pre>DeedleFake: <pre><pre><code>tmp = append(tmp, tmp[0:i, i+1:]) </code></pre> <p>That&#39;s a syntax error. You can&#39;t have a comma in an array access.</p></pre>UpOnCloud9: <pre><p>updated.</p></pre>skelterjohn: <pre><p>Appending single elements is amortized constant time. This is because you&#39;re adding something of a constant size.</p> <p>Appending an entire new slice takes at least O(n) for appending a slice of length n because it needs to be copied.</p></pre>TheMerovius: <pre><blockquote> <p>Appending single elements is amortized constant time. This is because you&#39;re adding something of a constant size.</p> </blockquote> <p>No, it&#39;s because <code>append</code> grows the underlying array by 2x when needed. A naive append, like</p> <pre><code>func append(s []int, v int) []int { s2 := make([]int, len(s)+1) copy(s2, s) s2[len(s)] = v return s2 } </code></pre> <p>would be <code>O(n)</code>, even though &#34;you&#39;re adding something of constant size&#34;.</p></pre>naapurisi: <pre><p>Your naive append doesn&#39;t copy the existing elements from s to s2.</p></pre>TheMerovius: <pre><p>true, brain fart :) Edited, thanks.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

455 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传