如何加快我的代码?

时间:2018-05-17 12:44:26

标签: c performance loops time-complexity

我想编写一个位分离代码,但我想知道如何才能提高代码的速度。我可以摆脱一些循环等吗?

代码的目标是分离数组的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;
}

1 个答案:

答案 0 :(得分:0)

  

我想知道如何提高代码的速度。我可以摆脱一些循环等吗?

每个测试用例的时间复杂度将为O(n),无论您做什么,因为在您知道何时停止打印零之前必须阅读所有数字。

现在,至于加速,你确实可以删除至少一个循环。提示:你不需要计算有多少个零,只需要计算多少个零。

相关问题