douqi1212 2019-07-23 11:37
浏览 64
已采纳

为什么这段代码在Go O(n²)中而不是O(n)中?

I'm in the middle of reading Effective Go, and there is a piece of code which I think is O(n) complexity yet it is O(n²). Why is this for range loop considered to be O(n²)?

It is found here (under #interfaces)

type Sequence []int
...
func (s Sequence) String() string {
    ...
    for i, elem := range s { // Loop is O(N²); will fix that in next example.
        if i > 0 {
            str += " "
        }
        str += fmt.Sprint(elem)
    }
    ...
}

The reason I think it is O(n) is because there is only one iteration over s, and the if statement and fmt.Sprint should not be in O(n) complexity.

  • 写回答

1条回答 默认 最新

  • drba1172 2019-07-23 11:44
    关注

    Every time you concatenate str += fmt.Sprint(elem) you create a new String that has to transfer (copy) the characters of the prev str into the new one. In step 1 you copy 1 char, in step 2, 2, etc. This gives n(n+1)/2 copies. Hence the complexity is O(n^2).

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

报告相同问题?

悬赏问题

  • ¥15 数据库原理及应用上机练习题
  • ¥30 征集Python提取PDF文字属性的代码
  • ¥15 如何联系真正的开发者而非公司
  • ¥15 有偿求苍穹外卖环境配置
  • ¥15 代码在keil5里变成了这样怎么办啊,文件图像也变了,
  • ¥20 Ue4.26打包win64bit报错,如何解决?(语言-c++)
  • ¥15 clousx6整点报时指令怎么写
  • ¥30 远程帮我安装软件及库文件
  • ¥15 关于#自动化#的问题:如何通过电脑控制多相机同步拍照或摄影(相机或者摄影模组数量大于60),并将所有采集的照片或视频以一定编码规则存放至规定电脑文件夹内
  • ¥20 深信服vpn-2050这台设备如何配置才能成功联网?