如何检查数组是否有任何重复?

时间:2011-11-20 04:15:22

标签: c arrays

我正在将文件内容读入9元素数组。我需要检查这个数组中是否有任何重复项。我需要这样做而无需重新排序或更改数组的任何内容。

我将如何做到这一点?

3 个答案:

答案 0 :(得分:14)

使用蛮力。

你在数组中只有9个元素,所以只需要36次比较就可以找到任何副本:

int count = sizeof(array) / sizeof(array[0]);

for (int i = 0; i < count - 1; i++) { // read comment by @nbro
    for (int j = i + 1; j < count; j++) {
        if (array[i] == array[j]) {
            // do whatever you do in case of a duplicate
        }
    }
}

答案 1 :(得分:-2)

您可以使用此方法:

// sort a copy of the array with the algorithm you like the most and then...
bool duplicates = false;
for(i = 0; i < 7; i++)
{
   if (array[i] == array[i+1])
   {
      duplicates = true;
      break;
   }
}

答案 2 :(得分:-5)

 int main()
 {
 srand(time(0));
 int data[10];

for(int c=0;c<=9;c++)
{
    bool found = false;
    while(!found)
    {
        data[c]=rand()%10+1;
        found=true;
        for(int r=0;r<c;r++)
        {
            if(data[c]==data[r]) found=false;
        }
    }
}

for(int c=0;c<=9;c++) cout << data[c] << endl;
return 0;
}
相关问题