下面的代码在内存方面的复杂性是多少?

发布于 2024-08-26 20:31:16 字数 661 浏览 6 评论 0原文

我从 这里阅读了有关 Big-O 表示法的内容< /a> 对计算复杂性有几个问题。因此,对于下面的代码,我计算了复杂性。需要您的投入。

    private void reverse(String strToRevers) 
    {
        if(strToRevers.length() == 0)
        {
            return ;
        }
        else 
        {
            reverse(strToRevers.substring(1));
            System.out.print(strToRevers.charAt(0));
        }
    }

如果考虑内存因素,那么上述代码对于 n 个字符的字符串的复杂度是 O(n^2)。解释是对于由 n 个字符组成的字符串,下面的函数将被递归调用 n-1 次,并且每个函数调用都会创建一个单个字符的字符串(stringToReverse.charAT(0))。因此,n*(n-1)*2 转换为 o(n^2)。让我知道这是否正确?

I read about Big-O Notation from here and had few questions on calculating the complexity.So for the below code i have calculated the complexity. need your inputs for the same.

    private void reverse(String strToRevers) 
    {
        if(strToRevers.length() == 0)
        {
            return ;
        }
        else 
        {
            reverse(strToRevers.substring(1));
            System.out.print(strToRevers.charAt(0));
        }
    }

If the memory factor is considered then the complexity of above code for a string of n characters is O(n^2). The explanation is for a string that consists of n characters, the below function would be called recursively n-1 times and each function call creates a string of single character(stringToReverse.charAT(0)). Hence it is n*(n-1)*2 which translates to o(n^2). Let me know if this is right ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

智商已欠费 2024-09-02 20:31:16

因此 n*(n-1)*2 转换为 o(n^2)。让我知道这是否正确?

差不多:是 n * (n-1) / 2,而不是 *2,这也是 O(n^2)。请注意,o(n^2)(小-O)意味着其他< /a>,所以区分很重要。

这是假设我们将其视为伪代码。特定于语言的实现和智能编译器可能能够显着提高运行时间。例如,可以观察到您只是反转字符串的编译器可能只是执行就地反转,即 O(n)。

Hence it is n*(n-1)*2 which translates to o(n^2). Let me know if this is right ?

Almost: it's n * (n-1) / 2, not *2, which is also O(n^2). Note that o(n^2) (little-O) means something else, so the distinction is important.

This is assuming we're considering this as pseudocode. Language-specific implementations and smart compilers may be able to improve the running time substantially. For instance, a compiler that can observe that you're simply reversing the string might just do an in-place reverse, which is O(n).

恋竹姑娘 2024-09-02 20:31:16

看起来像 Java,所以它不是 O(n**2)。这是因为字符串共享底层字符序列缓冲区;他们可以做到这一点,因为它们是不可变的对象。

但在栈空间中却是O(n)。那不好。最好分配一个可变的字符工作缓冲区,将字符串反转为该缓冲区,然后立即打印全部内容。

Looks like Java, so it's not O(n**2). That's because strings share the underlying character sequence buffers; they can do this because they are immutable objects.

But it is O(n) in stack space. That's not good. It's better to allocate a mutable working buffer of characters, reverse the string into that, and then print the whole lot at once.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文