【发布时间】: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]>=height){bricks[j]--; count++;}可以轻松更改为if (bricks[j]>=height){count+=heigth-bricks[j]+1;bricks[j]=height-1;}。 -
询问运行时问题时,请发帖minimal reproducible example
标签: c arrays for-loop optimization