C++ How To Find Duplicate Elements in an Array
Find Duplicate Elements in an Array
Use one set to remember the values you have seen, and another for the duplicates:
Example
int numbers[] = {1, 2, 3, 2, 4, 5, 4};
set<int> seen;
set<int> duplicates;
for (int num : numbers) {
if (seen.count(num)) {
duplicates.insert(num);
} else {
seen.insert(num);
}
}
cout << "Duplicates: ";
for (int num : duplicates) {
cout << num << " ";
}
Explanation:seen.count(num) is 1 if the number is already in seen, and 0 if it is not.
A number that was seen before is a duplicate, so it is added to duplicates.