查找数组中重复(重复)数字的索引
Find indexes of duplicated (repeated) numbers in an array
我有 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;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 数组索引的值没有增加
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 查找最接近的大于当前数字的数字的索引
- 使用移位的无符号数字作为数组的索引号是一种很好的做法
- 查找数组中重复(重复)数字的索引
- 如何以正确的时区从XTS索引中获取数字时间?
- 根据另一个数字的可整除性返回子数组中的索引
- 使用二叉搜索查找数字的第 N 次出现的索引
- 循环并将数字的索引用作文件名
- 尝试为数字值编制索引。C++ & Lua
- 尝试将数字乘以其索引
- 对数字及其索引列表进行排序的最快方法
- 为什么我可以索引到数字超出范围的三维数组中,但仍然可以访问数组中的最后一个数字
- 带有Overload[]运算符的C++MyInteger类,因此索引在位置i返回数字
- 如果用户从数组中输入数字,如何获取 2D 数组的索引
- 将数组中的所有数字更改为其索引值
- 用户正在输入10个数字,找到最大的负值及其索引/位置