我想检查数组中的重复值

时间:2015-01-18 02:30:49

标签: c

您好我很高兴知道这个网站提问。我有一个问题,我做了一个数组。然后我想检查数组中的匹配值。例如,

int array[5]={1,2,4,2,5} ;

因此,array[1]array[3]重复了值2。那么如何检查重复值?

使用for / if是检查相同值的唯一方法吗?

4 个答案:

答案 0 :(得分:1)

差不多。至少,这是做你想做的最简单的方法。如果您需要控制事件或类似情况,可能Map类型更适合您。

答案 1 :(得分:0)

你如何使用“qsort”?

qsort(( void * )array, 5 , sizeof( data[0] ) , my_sort );

my_sort是一个创建自己的函数。 例如,

int my_sort( const void * a , const void * b ) {
    if( *( int * )a < *( int * )b ) {
        return -1;
    }
    else
    if( *( int * )a == *( int * )b ) {
        // You can check here.

        return 0;
    }
    return 1;
}

答案 2 :(得分:0)

这取决于你的数组上是否存在int的大小限制。

如果您可以确定(并检查)数组中的所有元素都被限制在相对较小的范围内(例如,介于0到255之间),则可以使用单独的数组MAXVAL-MINVAL来跟踪数组中的每个元素首先出现在哪里。如果是这种情况,您可以快速签入O(n)(其中n是数组的大小)是否(甚至在哪里)有重复项。

它可能看起来像这样(警告:我没有检查甚至编译此代码)

#define COUNTOF(x) ( sizeof(x) / sizeof((x)[0]) )
int i, flags[MAXVAL-MINVAL];

for(i=0; i<COUNTOF(flags); i++) flags[i]=-1; // Initialize flags to 'not found'

for(i=0; i<COUNTOF(array); i++) 
{
    if (flags[array[i]-MINVAL]!=-1)   // Duplicate value found
      printf("Value %d was found in positions %d and %d\n",array[i], i, flags[array[i]-MINVAL]);
    else  // Value had not been found before
      flags[array[i]-MINVAL]=i;  // Keep track of where first seen
}

答案 3 :(得分:-1)

使用类似的东西:

int matchCount = 0;
for(int i = 0;i < (sizeof(array)/sizeof(int)); i++)
{
    for( int j=0; j<(sizeof(array)/sizeof(int)); j++)
    {
        if( i != j ) // skip when both indexes point to same location
        {
            if( array[i] == array[j] )
            {
                matchCount++;
            }
        }
    }
}

以上是针对整数数组的。 与其他大小类型的数组非常相似的代码

将计算两次匹配,因此将最终matchCount除以2

相关问题