[英]the time complexity difference between using arrays and vectors
for the question finding nth ugly number(whose prime factorisation only contains 2,3,5 ) (1 included).when i used the below solution using vectors the time taken is >1.013 which showed TLE but when i used arrays the time taken is 0.9 which got accepted?对于找到第 n 个丑数(其素因数分解仅包含 2,3,5 )(包括 1)的问题。当我使用以下使用向量的解决方案时,所花费的时间是 >1.013,这显示了 TLE,但是当我使用 arrays 时,所花费的时间是0.9 哪个被接受了? can anyone explain why this is happening?
谁能解释为什么会这样?
#include <bits/stdc++.h>
using namespace std;
#define llb long long int
int main() {
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
llb ugly[n]; // To store ugly numbers
llb i2 = 0, i3 = 0, i5 = 0;
llb next_multiple_of_2 = 2;
llb next_multiple_of_3 = 3;
llb next_multiple_of_5 = 5;
llb next_ugly_no = 1;
ugly[0] = 1;
for (int i=1; i<n; i++)
{
next_ugly_no = min(next_multiple_of_2,
min(next_multiple_of_3,
next_multiple_of_5));
ugly[i] = next_ugly_no;
if (next_ugly_no == next_multiple_of_2)
{
i2 = i2+1;
next_multiple_of_2 = ugly[i2]*2;
}
if (next_ugly_no == next_multiple_of_3)
{
i3 = i3+1;
next_multiple_of_3 = ugly[i3]*3;
}
if (next_ugly_no == next_multiple_of_5)
{
i5 = i5+1;
next_multiple_of_5 = ugly[i5]*5;
}
} /*End of for loop (i=1; i<n; i++) */
cout<<next_ugly_no<<endl;
}
return 0;
}
The performance should be virtually identical if you write the code correctly.如果您正确编写代码,性能应该几乎相同。
What is likely happening (since you don't show the other case) is that in the std::vector
case you are re-allocating many times, probably by re-creating the object on every outer loop iteration.可能发生的事情(因为您没有显示其他情况)是在
std::vector
情况下,您重新分配了很多次,可能是通过在每次外循环迭代时重新创建 object 。 If you re-use the object, then you should see very similar performance.如果您重新使用 object,那么您应该会看到非常相似的性能。
Side note:边注:
llb ugly[n]; // To store ugly numbers
This is non-standard C++: a Variable Length Array (VLA).这是非标准 C++:可变长度数组 (VLA)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.