如何降低此算法的计算复杂度?

时间:2018-05-05 17:59:22

标签: c++ performance time-complexity

我有这个算法:

int x[100001],n,j,k,i;
int maxi=0;

for (i=1; i<n; i++) {
    for (j=i+1; j<=n; j++) {
        bool ok=true;
        for (k=i+1; k<=j; k++) {
            if (x[i]<x[i-1]) {
                ok=false;
            }
        }
        if (ok == true) {
            if (j-i+1 > maxi) {
                maxi = j-i+1;
            }
        }
    }
}
cout << maxi;

如何降低复杂性,最初显然是 O(N^3) ,以提高算法效率?

1 个答案:

答案 0 :(得分:2)

好吧,尽管我可以从这个问题得到,这是我认为算法正在做的O(n ^ 2)版本(很糟糕)..

删除了内部边界循环,因为它没用。

int n_squared_FindLongestAscendingSubsequence(int* x, int n)
{
    int j, k, i;
    int maxi = 0;

    for (i = 1; i<n; i++) {
        for (j = i + 1; j <= n; j++) {
            if (x[j]<x[j - 1]) 
            { // found the point where the seq descends
                if (j - i > maxi) // if it is longer then what we found?
                    maxi = j - i;
            }
        }
    }
    return maxi;
}

O(n)中的另一个解决方案:

int n_FindLongestAscendingSubsequence(int* x, int n)
{
    int maxi = 0;
    int anchor = 0; // will save the index from where it ascends
    int prev = -2 ^ 31;
    for (int i = 1; i < n; i++)
    {
        if (x[i] < x[i-1])
        { // found a point where the seq descends
            if (i - anchor > maxi) // if it is longer then what we found?
                maxi = i - x[i];
            anchor = i; // no point going to 'anchor+1', because all seq will be shorter untill 'i'.
        }
    }
    return maxi;
}