What is the complexity of this simple piece of code?

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

    I think these text in the book must be a typo ,I think the right content is below,I fix it:

    ===================================================================

    Question: What is the running time of this code?

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

    Answer: O(n2), where n is the number of letters in sentence. Here’s why: each time you append a string to sentence, you create a copy of sentence and run through all the letters in sentence to copy them over. If you have to iterate through up to n characters each time in the loop, and you’re looping at least n times, that gives you an O(n2) run time. Ouch! With StringBuffer (or StringBuilder) can help you avoid this problem.

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

    =====================================================================

    Am i right?

提交回复
热议问题