简体   繁体   English

这个程序的运行时和空间复杂度是多少?

[英]What is the Runtime and Space Complexity of this program?

Problem Statement: Reverse the words.问题陈述:颠倒单词。

Example: perfect makes practice Output: practice makes perfect示例:完美使实践输出:实践使完美

I am pretty sure the space complexity is O(n) as I am using StringBuilder but still I wanna be sure.我很确定空间复杂度是 O(n),因为我使用的是 StringBuilder,但我仍然想确定。 I am learning Runtime complexity and from below I learned that both loops are running for O(n) elements.我正在学习运行时复杂性,从下面我了解到两个循环都在为 O(n) 个元素运行。 strB.toString() it internally copies the characters and returns the String which I think is also an O(n) task. strB.toString() 它在内部复制字符并返回字符串,我认为这也是一个 O(n) 任务。 The same goes for strB.append(arr[i]) as when the StringBuilder capacity got exhausted it will again call Arrays.copyOf and will create new Character array internally which I think is still O(n). strB.append(arr[i]) 也是如此,当 StringBuilder 容量耗尽时,它会再次调用 Arrays.copyOf 并将在内部创建新的 Character 数组,我认为它仍然是 O(n)。

I am trying to learn run-time and space complexity but sometimes get stuck.我正在尝试学习运行时和空间复杂性,但有时会卡住。 I think this whole solution runtime complexity is O(n2), please let me know your views.我认为整个解决方案的运行时复杂度是 O(n2),请让我知道您的看法。

Follow up question: If it is O(n2) then it means that we can't use java internal DS methods for solving interview questions?追问:如果是O(n2)那么就不能用java内部的DS方法解决面试题了?

public class CharReverseAsWords {
public static void main(String[] args) {
    char[] arr = { 'p', 'e', 'r', 'f', 'e', 'c', 't', ' ', 'm', 'a', 'k', 'e', 's', ' ', 'p', 'r', 'a', 'c', 't',
            'i', 'c', 'e' };
    long startTime = System.currentTimeMillis();

    //Creating Stack.
    Deque<String> stk = new ArrayDeque<>();

    StringBuilder strB = new StringBuilder(26);
    for (int i = 0; i < arr.length; i++) {  //O(n)
        if (arr[i] != ' ') {
            strB.append(arr[i]);           //O(n): If capacity is consumed, new array will get created which has O(n) time complexity.
        } else {
            stk.push(strB.toString());      //O(1)
            stk.push(" ");                  //O(1)
            strB = new StringBuilder(26);
        }
    }

    //pushing last string
    stk.push(strB.toString());          //O(1)

    while (!stk.isEmpty()) {            //O(n)
        System.out.print(stk.pop());    //O(1)
    }

    System.out.println();
    System.out.println(System.currentTimeMillis() - startTime + " ms");
}}

As per your code, it would be O(n)+O(n)+O(n) = O(3n) .根据您的代码,它将是O(n)+O(n)+O(n) = O(3n)

for (int i = 0; i < arr.length; i++) {  //O(n)
    // ---- //
}

//pushing last string
stk.push(strB.toString());          //O(n)

while (!stk.isEmpty()) {            //O(n)
    System.out.print(stk.pop());
}

But, when we calculate complexity with n inputs, constants would not affect much .但是,当我们用n输入计算复杂度时,常量不会影响太大 That means, O(3n) would be O(n) by ignoring constants.这意味着,通过忽略常量, O(3n)将是O(n)

Answer 1 : Your programme's Time complexity is O(n)答案 1:您程序的时间复杂度为O(n)

Answer 2 : There are trade-offs between both.答案 2:两者之间存在权衡。 We can use collection framework methods of java in DS problems.我们可以在DS问题中使用java的集合框架方法。 But, always we need to think if we can achieve the same with our logic and loop, we should go for that.但是,我们总是需要考虑是否可以通过我们的逻辑和循环实现相同的目标,我们应该这样做。 We can take care of not generating more garbage objects , more computation than necessary and breaking loops as soon as possible kind of points of optimisations.我们可以注意不产生更多的garbage objectsmore computation than necessarybreaking loops as soon as possible类型的优化点。 If we go for collection framework, these points may be considered as trade-offs.如果我们采用集合框架,这些点可能被视为权衡。

A little optimisation in your code would be :您的代码中的一些优化将是:

for (int i = 0; i < arr.length; i++) {  //O(n)
    // ---- //

    // On last iteration, we can push last string 
    if(i == arr.length - 1) {
        //pushing last string
        stk.push(strB.toString())
    }
}

This is complexity.这就是复杂性。
That's why这就是为什么

// time: O(N)
for (int i = 0; i < arr.length; i++)

// space: O(N)
char[] arr
Deque<String> stk

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM