What is the complexity of this simple piece of code?

前端 未结 10 1256
遇见更好的自我
遇见更好的自我 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 05:11

    Here's my calculation for how they got O(n^2)

    We'll ignore the CPU time for declaring the StringBuffer, as it doesn't vary with the size of the final string.

    When calculating the O complexity we are concerned with the worst case, this will occur when there are 1 letter Strings. I shall explain after this example:

    Let's say we have 4 one-letter strings: 'A', 'B', 'C', 'D'.

    Read in A: CPU-time to find end of StringBuffer: 0 CPU-time to append 'A': 1

    Read in B: CPU-time to find end of StringBuffer: 1 CPU-time to append 'B': 1

    Read in C: CPU-time to find end of StringBuffer: 2 CPU-time to append 'C': 1

    Read in D: CPU-time to find end of StringBuffer: 3 CPU-time to append 'D': 1

    CPU-time to copy StringBuffer to String at the end: 4

    Total CPU-time = 1 + 2 + 3 + 4 + 4

    If we generalise this to n 1-letter words:

    1 + 2 + 3 + ...... + n + n = 0.5n(n+1) + n

    I did this by using the formula for the sum of an arithmetic sequence.

    O(0.5n^2 + 1.5n) = O(n^2).

    If we use multi-letter words, we are going to have to find the end of the StringBuffer less frequently, leading to a lower CPU-time and a 'better' case.

提交回复
热议问题