[英]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.