What is the complexity of this simple piece of code?

前端 未结 10 1271
遇见更好的自我
遇见更好的自我 2020-11-29 04:28

I\'m pasting this text from an ebook I have. It says the complexity if O(n2) and also gives an explanation for it, but I fail to see how.

Question: What i

10条回答
  •  野性不改
    2020-11-29 04:57

    The accepted answer is just wrong. StringBuffer has amortized O(1) append, so n appends will be O(n).

    If it wasn't O(1) append, StringBuffer would have no reason to exist, since writing that loop with plain String concatenation would be O(n^2) as well!

提交回复
热议问题