What is the complexity of this simple piece of code?

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

    There's a typo in this book.


    1st case :

    public String makeSentence(String[] words) {
        String sentence = new String();
        for (String w : words) sentence += w;
        return sentence;
    }
    

    Complexity : O(n^2) -> (n words) x (n characters copied at each iteration, for copying the current sentence into a StringBuffer)


    2nd case :

    public String makeSentence(String[] words) {
        StringBuffer sentence = new StringBuffer();
        for (String w : words) sentence.append(w);
        return sentence.toString();
    }
    

    Complexity : O(n) -> (n words) x O(1) (amortized complexity for StringBuffer concatenation)

提交回复
热议问题