欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

删掉数组中重复的元素

程序员文章站 2024-03-17 15:13:22
...

原数组 a[] = {1,2,3,4,5,3,7,};
示例一(删掉数组中重复的后部分元素)

  • 输出:

a[]={1,2,3,4,5,7,}

# include<stdio.h>

int main()
{
    int a[] = {1,2,3,4,5,3,7,};
    int i,t;
    int k = 0;
    for (i = 0;i < sizeof(a)/sizeof(a[0]); i ++) {
        for (t = 0; t < i; t ++) {
            if (a[i] == a [t]) 
                break;            
        }
        if (t == i)      
            a[k++] = a[i];
    }

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

    return 0;
}

示例二(删掉数组中重复的前部分元素)

  • 输出:

a[]={1,2,4,5,3,7,}

# include<stdio.h>

int main()
{
    int a[] = {1,2,3,4,5,3,7,};
    int i,t;
    int k = 0;
    for (i = 0;i < sizeof(a)/sizeof(a[0]); i ++) {
        for (t = i+1; t < sizeof(a)/sizeof(a[0]); t ++) {
            if (a[i] == a [t]) 
                break;            
        }
        if (t == sizeof(a)/sizeof(a[0]))      
            a[k++] = a[i];
    }

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

    return 0;
}