簡體   English   中英

使用 arrays 和向量之間的時間復雜度差異

[英]the time complexity difference between using arrays and vectors

對於找到第 n 個丑數(其素因數分解僅包含 2,3,5 )(包括 1)的問題。當我使用以下使用向量的解決方案時,所花費的時間是 >1.013,這顯示了 TLE,但是當我使用 arrays 時,所花費的時間是0.9 哪個被接受了? 誰能解釋為什么會這樣?

#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;
}

如果您正確編寫代碼,性能應該幾乎相同。

可能發生的事情(因為您沒有顯示其他情況)是在std::vector情況下,您重新分配了很多次,可能是通過在每次外循環迭代時重新創建 object 。 如果您重新使用 object,那么您應該會看到非常相似的性能。


邊注:

llb ugly[n]; // To store ugly numbers

這是非標准 C++:可變長度數組 (VLA)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM