查找数组中重复(重复)数字的索引

Find indexes of duplicated (repeated) numbers in an array

本文关键字:数字 索引 重复 数组 查找      更新时间:2023-10-16

我有 2 个数组,其中arr1存储一个数字(薪水(,arr2存储一个字符串(员工姓名(。由于两个数组是链接的,我无法更改arr1的顺序或对其进行排序。我正在寻找一种更有效的方法来解决问题,即查找数组中是否有任何重复项。它可能有多个重复项,但如果没有找到,则应打印"未找到重复项"。

int count = 0;
for (int i = 0;i<arr_size ;i++)
{
for (int j = 0; j < arr_size && i != j; j++)
{
if (arr[i] == arr[j])
{
cout << arr2[i] << " " << arr1[i] << endl;
cout << arr2[j] << " " << arr1[j] << endl;
count ++;
}
}   
}
if (count == 0)
{
cout << "No employee have same salaries"<<endl;
}

我不想用这种低效的方式来解决问题。还有更好的建议吗?感谢您的帮助:) 而且这个问题还要求我打印出所有重复的员工和工资对

您可以使用具有平均恒定时间插入和检索的unordered_set

#include <unordered_set>
// ...set up arr
int count = 0;
std::unordered_set<int> salaries;
for (int i = 0; i < arr_size; i ++) {
if (salaries.count(arr[i]) > 0) {
// it's a duplicate
}
salaries.insert(arr[i]);
}
// do more stuff

使用unordered_map创建一个Haspmap,并存储工资和工资指数。 现在,如果存在相同的薪水,则增加计数

您可以通过使用unordered_set来将算法的时间复杂度降低到 O(n(,以牺牲使用额外空间为代价。

#include<unordered_set>
int main(){
// Initialise your arrays
unordered_set<string> unique;
bool flag = false;
for(int i=0;i<arr_size;i++){
// Since unordered_set does not support pair out of the box, we will convert the pair to string and use as a key
string key = to_string(arr1[i]) + arr2[i];
// Check if key exists in set
if(unique.find(key)!=unique.end())
unique.push(key);
else{
// mark that duplicate found
flag = true;
// Print the duplicate
cout<<"Duplicate: "+to_string(arr1[i])+"-"+arr2[i]<<endl;
}
}
if(!flag){
cout<<"No duplicates found"<<endl;
} else cout<<"Duplicates found"<<endl;
return 0;
}