如何打印唯一元素的数量,而不是在代码中显示元素本身



我想打印唯一元素的数量,而不是显示元素。例如show 4。意味着我们有4个独特的元素

#include<stdio.h>
#define max 100
int ifexists(int z[], int u, int v)
{
int i;
for (i=0; i<u;i++)
if (z[i]==v) return (1);
return (0);
}
void main()
{
int p[max], q[max];
int m;
int i,k;
k=0;
printf("Enter length of the array:");
scanf("%d",&m);
printf("Enter %d elements of the arrayn",m);
for(i=0;i<m;i++ )
scanf("%d",&p[i]);
q[0]=p[0];
k=1;
for (i=1;i<m;i++)
{
if(!ifexists(q,k,p[i]))
{
q[k]=p[i];
k++;
}
}
printf("nThe unique elements in the array are:n");
for(i = 0;i<k;i++)
printf("%dn",q[i]);
}

https://onlinegdb.com/Bk3tvQMpw

对数组进行排序,然后遍历元素,如果当前元素与上一个元素不同,则打印出来:

int cmpint(const void *a, const void *b) {
return *(int *) a) < *(int *) b :
-1 ?
(
*(int *) b) < *(int *) a ?
1 :
0
);
}

int main() {
/* ... */
qsort(p, m, sizeof(*p), cmpint);
int n = 0;
for(int i = 0; i < m; i++) {
if(!i || p[i-1] != p[i]) n++;
}
printf("Number of unique elements: %dn", n);
}

根据示例代码,p是现在排序的数组,长度是m。由于qsort预计为O(m*log(m((,因此该算法也将如此。如果不对数组进行排序,则由于m个线性搜索,数组将为O(m^2(。

如果我正确理解了这个问题,您需要的是使用函数计算数组中的唯一元素,而不定义辅助数组。也就是说,不需要输出唯一元素本身。

在这种情况下,相应的函数可以如下所示,如下面的演示程序所示。

#include <stdio.h>
int is_unique( const int a[], size_t n, int value )
{
while ( n != 0 && a[ n - 1 ] != value ) --n;

return n == 0;
}
int main(void) 
{
int a[] = { 1, 2, 3, 3, 2, 1 };
const size_t N = sizeof( a ) / sizeof( *a );

size_t count = 0;

for ( size_t i = 0; i < N; i++ )
{
count += is_unique( a, count, a[i] );
}

printf( "There are %zu unique elements in the array.n", count );

return 0;
}

程序输出为

There are 3 unique elements in the array.

如果您不想再定义一个函数来计算数组中的唯一元素,那么只需将上面演示程序中显示的函数中的循环移动到main中即可。

给你。

#include <stdio.h>
int main(void) 
{
int a[] = { 1, 2, 3, 3, 2, 1 };
const size_t N = sizeof( a ) / sizeof( *a );

size_t count = 0;

for ( size_t i = 0; i < N; i++ )
{
size_t j = i;

while ( j != 0 && a[j - 1] != a[i] ) --j;

count += j == 0;
}

printf( "There are %zu unique elements in the array.n", count );

return 0;
}

程序输出与上面显示的相同

There are 3 unique elements in the array.

注意,根据C标准,无参数的功能主体应像一样声明

int main( void )

而不是

void main()

最新更新