我有以下代码是我为编码竞赛中的一个实践问题编写的,但是当我运行它时,我会花费很多时间。罪魁祸首(我猜)是在O(n ^ 2)中运行的double for循环。有什么办法可以优化此代码?我已经尝试过弄些记忆,但是我不知道该怎么做。

for (i=n;i>0;i--){
    int index = linearSearch(seq,i,n);
    int height = bricks[index];
    for (j=0;j<n;j++){
        if (j != index){
            if (bricks[j] >= height){
                while(bricks[j]>=height){
                    bricks[j]--;
                    count++;
                }

                if(bricks[j] < 0){
                    printf("-1\n");
                    return 0;
                }

            }
        }
    }

    bricks[index] = 0;
    seq[index] = 0;
}

最佳答案

我不确定发布的代码段的目标,但是以下建议的代码可能会有助于延长执行时间:

for ( i=n; i>0; i-- )
{
    int index  = linearSearch(seq,i,n);
    int height = bricks[index];

    for ( j=0; j<n ; j++ )
    {
        if( j != index )
        {
            if( bricks[j] >= height )
            {
                count += bricks[j] - height;
                bricks[j] -= bricks[j] - height;
            }
        }
    }

    bricks[index] = 0;
    seq[index] = 0;
}

关于c - 优化数组的双重迭代,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45821730/

10-12 18:31