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

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

我该怎么做呢?

使用蛮力。

你在数组中只有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 } } } 

您可以使用此方法:

 // 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; } } 
  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