简体   繁体   English

以下代码段的时间复杂度是否为O(n ^ 2)?

[英]Is the time complexity of the following snippet O(n^2)?

I was wondering if the time complexity of the following code snippet is O(n^2) : 我想知道以下代码片段的时间复杂度是否为O(n^2)

class Solution {
public:

    int numSquares(int n) {
        if(n<=0)
            return 0;

        vector<int> dp(n+1, INT_MAX);
        dp[0]=0;
        for(int i=1; i<=n; i++) {
            for(int j=1; j*j<=i; j++) {
                //+1 because you are adding the current `j`
                dp[i]=min(dp[i], dp[i-j*j]+1);
            }
        }

        return dp[n];
    }
};

I am not sure because in the inner loop, we are checking for perfect squares less than i , which would be very less in comparison to i (and I think so less, that they can be assumed to be constant). 我不知道,因为在内部循环,我们正在检查完全平方不到i ,这将是非常少的相比, i (我是这么认为的少,他们可以被假定为常数)。 In this case then, the complexity would be just O(n) . 那么,在这种情况下,复杂度仅为O(n) So, can I say that the complexity is O(n) or is it O(n^2) ? 那么,我可以说复杂度是O(n)还是O(n^2)

Note: The code snippet is a solution to a question from LeetCode.com which apparently has a collection of interview questions. 注意:该代码段是LeetCode.com上一个问题的解决方案,该问题显然包含一系列面试问题。

The outer loop is O(N) . 外循环为O(N)
The inner loop is O(sqrt(i)) . 内部循环是O(sqrt(i))

The sum will be: 总和为:

1 + sqrt(2) + ... + sqrt(N)

It's greater than O(N) but is less than O(N^2) . 它大于O(N)但小于O(N^2)

Without going into a very accurate computation of the above sum, I would say, it's close to O(N*sqrt(N)) . 在不对上述总和进行非常精确的计算的情况下,我会说它接近O(N*sqrt(N))

Update 更新资料

From http://ramanujan.sirinudi.org/Volumes/published/ram09.pdf , the above sum is: http://ramanujan.sirinudi.org/Volumes/published/ram09.pdf中 ,上述总和为:

C1 + (2.0/3)*N*SQRT(N) + (1.0/2)*SQRT(N) + ....

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

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