【问题标题】:Optimizing double iteration over arrays优化数组的双重迭代
【发布时间】:2018-01-30 23:33:51
【问题描述】:

我有以下代码是我为编码竞赛中的一个练习题编写的,但是当我运行它时,我会超时。罪魁祸首(我猜)是在 O(n^2) 中运行的双 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;
}

【问题讨论】:

  • 如果这是工作代码,你应该把它带到codereview。但是在你这样做之前,请确保写一个好的解释你的代码,例如记录它
  • 这段代码应该做什么
  • 快速浏览一下,优化这段代码的方法有很多...
  • while(bricks[j]&gt;=height){bricks[j]--; count++;} 可以轻松更改为 if (bricks[j]&gt;=height){count+=heigth-bricks[j]+1;bricks[j]=height-1;}
  • 询问运行时问题时,请发帖minimal reproducible example

标签: c arrays for-loop optimization


【解决方案1】:

我不确定发布代码 sn-p 的目的,但以下建议的代码可能有助于执行持续时间:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多