สมมติว่ามีอาร์เรย์ของจำนวนเต็ม N ตัว ที่นี่เราจะพิมพ์ค่าซ้ำของอาร์เรย์ที่กำหนด หากไม่มีค่าซ้ำ ให้คืนค่า -1 ดังนั้นถ้าอาร์เรย์เป็น [12, 15, 12, 3, 6, 12, 3, 48, 56, 8, 48] ค่าซ้ำคือ [12, 3, 48]
ที่นี่เราจะใช้ unordered map ใน C++ ดังนั้นตอนแรกเมื่อเอาองค์ประกอบหนึ่ง ตรวจสอบว่ามันมีอยู่ใน map หรือไม่ หากมีอยู่ ให้พิมพ์มันเป็นค่าซ้ำ มิฉะนั้นเพิ่มมันเข้าไปใน map
ตัวอย่าง
#include <iostream>
#include <unordered_map>
using namespace std;
void displayDuplicates(int arr[], int n) {
unordered_map<int, int> occurrence;
for (int i = 0; i < n; i++)
occurrence[arr[i]]++;
bool duplicate = false;
unordered_map<int, int>::iterator itr;
for (itr = occurrence.begin(); itr != occurrence.end(); itr++) {
if (itr->second > 1) {
cout << itr->first << " ";
duplicate = true;
}
}
if (duplicate == false)
cout << "-1";
}
int main() {
int arr[] = {12, 15, 12, 3, 6, 12, 3, 48, 56, 8, 48};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Duplicate elements are: ";
displayDuplicates(arr, n);
}
ผลลัพธ์
Duplicate elements are: 12 3 48