c - 如何加速我的代码?

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

最佳答案

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/

相关文章:

javascript - 循环遍历数组中的第一层并将其分配给变量

c - 将整数文字添加或分配给 size_t

c++ - Eclipse CDT + ICC 编译器

.net - 文本数据最快的哈希算法

java - 为什么在预热阶段浮点运算要快得多?

asp.net - Umbraco 版本 5 出了什么问题?

python - 在有条件的循环中列出索引超出范围

python - 如何在python中的线程循环中引发异常?

c - 注释风格会影响二进制大小吗?

C - 返回指向数组的指针