c语言判断两个数组是否相同,不考虑把顺序和重复元素

总体思路:先对数组排序,然后去掉重复元素,对比两个去重以后的数组长度是否相同,若不同则两个数组不一致,若相同,则依次判断两个数组对应的元素是否相同,若出现一处不同,则不一致。 

#include <stdio.h>
#include <stdlib.h>

int insort(int k[],int n); // 排序去除重复元素

int main()
{
    //input array1
    printf("Please input array1:");
    int i1=0,n1=0;
    int *a1=(int*)malloc(n1*sizeof(int));
    char b;
    while((b=getchar())!='\n')
    {
        ungetc(b,stdin);
        a1 = (int*)realloc(a1,++n1*sizeof(int));
        scanf("%d",&a1[i1++]);
    }
    //input array2
    printf("Please input array2:");
    int i2=0,n2=0;
    int *a2=(int*)malloc(n2*sizeof(int));
    while((b=getchar())!='\n')
    {
        ungetc(b,stdin);
        a2 = (int*)realloc(a2,++n2*sizeof(int));
        scanf("%d",&a2[i2++]);
    }

    //show array
    printf("\narray1: ");
    for (i1=0;i1<n1;i1++)
        printf("%d ",a1[i1]);
    printf("\narray2: ");
    for (i2=0;i2<n2;i2++)
        printf("%d ",a2[i2]);
    printf("\n");

    //sort two array
    int length1 = insort(a1, n1);
    int length2 = insort(a2, n2);

    if(length1 == 1){
        if (a1[0] != a2[0])
        {
            printf("array1 and array2 is not identical!\n");
        }
    }
    else
    {
        if(length1 != length2)
        {
            printf("array1 and array2 is not identical!");
        }
        else
        {
        	int i = 0;
            for(i=0; i<length1; i++)
            {
                if (a1[i] != a2[i])
                {
                    printf("array1 and array2 is not identical!\n");
                    break;
                }
            }
            if(i == length1) // 对比完所有数组都相同 则两个数组相同
            {
            	printf("array1 and array2 is identical!\n");
            }
        }
    }

    //release 
    free(a1);
    a1 = NULL;
    free(a2);
    a2 = NULL;
    return 0;
}

// sort and remove same element
int insort(int k[],int n){
    int q = n;
    for (int i = 0; i < q; i++)
    {
        int m = i;
        for (int j = m + 1; j < q; j++)
        {
            if (k[m] > k[j]) 
            {
                m = j;
            }
            else
            {
                if (k[m] == k[j])
                {
                    int t = k[q - 1];
                    k[q - 1] = k[j];
                    k[j] = t;
                    q--;
                    j--;
                }
            }
        }
        if (m != i)
        {
            int t = k[m];
            k[m] = k[i];
            k[i] = t;
        }
    }
    return q;
}


  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值