gpt4 book ai didi

c - 如何检测数组中的重复项并打印非重复项?

转载 作者:行者123 更新时间:2023-11-30 16:58:21 25 4
gpt4 key购买 nike

    void main ()
{
int x[19]={0}, i=0, y=0, u=0, p;
while (i<=19)
{
scanf("%d",&x[i]);
i=i+1;
}
for (i=u;i<=19;i++)
{
if (x[y]!=x[i+1])
p=x[y];
else
{
u++;
y++;
}
}
printf("%d",p);
}

所以我用它来检查重复项&它应该打印非重复项,但是正如你所看到的,如果所有都是重复项,但只有一个重复项,则此方法有效,如 x[0]=1 x[1]=1 x[3]=9 x[4]=1 ... x[19]=1;

    prints 
9

那么如何打印不重复的内容呢?有什么帮助吗?

最佳答案

这将是最简单的解决方案,只需嵌套一个额外的 for 循环即可。然而,这需要 O(n^2)。根据数组的大小,查看快速排序可能会有所帮助。

void main() {
int x[4] = { 1, 3, 2, 1 };

size_t i, j;
for (i = 0; i < sizeof(x) / sizeof(int); i ++) {
// Note that we only have to go to the last value before i.
for (j = 0; j < i; j ++) {
// We break if the value is a duplicate.
if (x[i] == x[j])
break;
}

// Check if the inner loop was break'ed (j < i) or not (j == i).
if (j == i)
printf("Unique: %i\n", x[i]);
}
}

还有一件事:如果在编译期间已知 x 的大小,则仅使用 sizeof(x)/sizeof(int) 。这里就是这种情况,但不要将其与 malloc 一起使用。

关于c - 如何检测数组中的重复项并打印非重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38926819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com