我想编写一个位隔离代码,但我不知道如何才能提高代码的速度。我可以摆脱一些循环等吗?
代码的目的是分隔数组的 1 和 0。 0 应该在左边,1 应该在右边。
这是我的代码:
#include <stdio.h>
int main() {
//code
int testCase;
scanf("%d\n", &testCase);
while(testCase>0) {
int n;
scanf("%d\n", &n);
int countzero = 0;
while(n>0) {
int i;
scanf("%d ", &i);
if(i==0){
countzero++;
}
}
for(int i=0; i<countzero; i++) {
printf("0");
}
for(int i=countzero; i<n ; i++) {
printf("1");
}
printf("\n");
}
return 0;
}
最佳答案
I wonder what can I do to increase the speed of the code. Can I get rid of some loops etc?
无论您做什么,每个测试用例的时间复杂度都是 O(n),因为您必须先读取所有数字,然后才能知道何时停止打印零。
现在,说到加速,你确实可以删除至少一个循环。提示:您不需要计算有多少个零,只需计算有多少个。
关于c - 如何加速我的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50391816/