c - 删除 C 数组中的重复数字 :

标签 c arrays algorithm duplicates complexity-theory

#include <stdio.h>

int main()
{
    int array[20], t = 0; //20-t is the new size of array.

    for(int i = 0; i<20; i++)
        scanf("%d", &array[i]);

    for(int i = 0; i<20-t; i++)
    {
        for(int j = i+1; j<20-t; j++)
        {
            if(array[i] == array[j])
            {
                for(int z = j; z<20-t; z++)
                    array[z] = array[z+1];//shift numbers.
                    t++; 
                    i = -1;
            }
        }
    }
}

这个程序工作正常,但我不知道为什么当 i = -1 时它可以工作,但当 i = 0 时却不能?我也想知道这段代码的复杂程度。

for(int i = 0; i<20-t; i++)
    printf("%d ", array[i]); //Array after duplicates have been removed.
    return 0;
}

最佳答案

如果你按照下面的方式编写程序

#include <stdio.h>

#define N   20

int main( void )
{
    int a[N];
    int n;
    int i;

    for ( i = 0; i < N; i++ ) scanf( "%d", &a[i] );

    n = 0;
    for ( i = 0; i < N; i++ )
    {
        int j = 0;
        while ( j < n && a[i] != a[j] ) ++j;
        if ( j == n ) a[n++] = a[i];
    }

    for ( i = 0; i < n; i++ ) printf( "%d ", a[i] );
    printf( "\n" );

    return 0;
}

那么算法的复杂度将为O( N ^ 2 )。

对于你的算法来说,它的复杂度是 O( N ^ 3 )。

那是你的方法效率较低。

关于c - 删除 C 数组中的重复数字 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33845899/

相关文章:

javascript - 比较两个对象数组,如果不存在则推送

c - gcc 编译没有错误,没有返回类型(即使使用 -Wall)

java - java中向数组添加变量元素

c - 在 if 语句中使用数组旁边的感叹号意味着什么? "if (!used[i])"

javascript - 将日期字符串转换为数组

java - Java 中的 K-Ary 树实现 : how to?

python - 如何更改字典值中字符串中的数字?

r - R 中中介分析的分步操作方法

c - 如何使用参数和标准输入作为输入来调试 C 程序

c - 指向数组的特定值