Big O, what is the complexity of summing a series of n numbers?

后端 未结 10 753
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 01:16

I always thought the complexity of:

1 + 2 + 3 + ... + n is O(n), and summing two n by n matrices would be O(n^2).

But today I read from a textbo

10条回答
  •  情深已故
    2020-12-14 02:07

    So my guess is that this is actually a reference to Cracking the Coding Interview, which has this paragraph on a StringBuffer implementation:

    On each concatenation, a new copy of the string is created, and the two strings are copied over, character by character. The first iteration requires us to copy x characters. The second iteration requires copying 2x characters. The third iteration requires 3x, and so on. The total time therefore is O(x + 2x + ... + nx). This reduces to O(xn²). (Why isn't it O(xnⁿ)? Because 1 + 2 + ... n equals n(n+1)/2 or, O(n²).)

    For whatever reason I found this a little confusing on my first read-through, too. The important bit to see is that n is multiplying n, or in other words that is happening, and that dominates. This is why ultimately O(xn²) is just O(n²) -- the x is sort of a red herring.

提交回复
热议问题