-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathduplicatearr.cpp
More file actions
43 lines (33 loc) · 1.23 KB
/
duplicatearr.cpp
File metadata and controls
43 lines (33 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
using namespace std;
void findDuplicates(int arr[], int size) {
// Assuming the numbers are in the range [-1000, 1000]
const int range = 2001; // Range from -1000 to 1000
int offset = 1000; // To handle negative numbers by shifting them to positive indexes
// Dynamically allocate memory for the hash map (frequency array)
int* freqMap = new int[range](); // Initialize all values to 0
cout << "Duplicates found: ";
bool foundDuplicate = false;
// Traverse the array and count the frequency of each element
for (int i = 0; i < size; ++i) {
int index = arr[i] + offset; // Shifting element to a valid index
freqMap[index]++;
// If the frequency is greater than 1, it's a duplicate
if (freqMap[index] == 2) {
cout << arr[i] << " ";
foundDuplicate = true;
}
}
// If no duplicates were found
if (!foundDuplicate) {
cout << "No duplicates found.";
}
delete[] freqMap; // Free the dynamically allocated memory
}
int main() {
int arr[] = {4, 3, 6, 7, 4, 8, 3, 2, 5}; // Example input
int size = sizeof(arr) / sizeof(arr[0]);
findDuplicates(arr, size);
cout << endl;
return 0;
}