当元素不限于C ++中的范围时,在给定数组中查找重复项
假设我们有N个整数组成的数组。在这里,我们将打印给定数组的重复项。如果不存在此类重复项,则返回-1。因此,如果数组类似于[12、15、12、3、6、12、3、48、56、8、48],则重复项为:[12、3、48]
在这里,我们将使用C++中的无序映射。因此,首先使用一个元素时,请检查映射中是否存在该元素(如果存在),然后简单地将其打印为重复,否则只需将其添加到映射中即可。
示例
#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
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短