我在 C++ 中编写了这段代码,作为 uni 任务的一部分,我需要确保数组中没有重复项:
// Check for duplicate numbers in user inputted data
int i; // Need to declare i here so that it can be accessed by the 'inner' loop that starts on line 21
for(i = 0;i < 6; i++) { // Check each other number in the array
for(int j = i; j < 6; j++) { // Check the rest of the numbers
if(j != i) { // Makes sure don't check number against itself
if(userNumbers[i] == userNumbers[j]) {
b = true;
}
}
if(b == true) { // If there is a duplicate, change that particular number
cout << "Please re-enter number " << i + 1 << ". Duplicate numbers are not allowed:" << endl;
cin >> userNumbers[i];
}
} // Comparison loop
b = false; // Reset the boolean after each number entered has been checked
} // Main check loop
它工作得很好,但我想知道是否有更优雅或更有效的检查方式。
原文由 Saladin Akara 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以在 O(nlog(n)) 中对数组进行排序,然后只需查看下一个数字。这比您现有的 O(n^2) 算法快得多。代码也干净了很多。您的代码也不能确保在重新输入时没有插入重复项。您需要首先防止重复存在。
我还建议使用 std::set - 那里没有重复项。