使用哈希图打印第一个重复元素;
print first repeating element using hashmap;
#include <bits/stdc++.h>
using namespace std;
int main() {
unordered_map<int,int>h;
int T;
int n,i;
cin>>T;
while(T--)
{ int flag=0;
cin>>n;
int arr[n];
for( i=0;i<n;i++)
{
cin>>arr[i];
}
for(i=0;i<n;i++)
{
h[i]=count(arr,arr+n,arr[i]);
}
for(auto x: h)
{
if(x.second>1)
{ flag=1;
cout<<x.first<<endl;
break;
}
}
if(flag==0)
{ cout<<-1<<endl;
}
}
}
给定一个整数数组。任务是找到数组中的第一个重复元素,即多次出现且首次出现的索引最小的元素。
我得到了无限的结果。 我什么没有错。 测试用例如下
输入:
test case :1
array size:7
array(1 5 3 4 2 4 5 )
输出:
2
由于您使用的是std::unordered_map
,该方法应该非常简单:
Set the minimum position to a large value.
Loop on the number data from first item to last.
If the number does not exist in the map, then
Add the item and position to the map
else
Set the minimum position to min(minimum position, position found in map)
不需要flag
变量(这几乎总是会导致某处出现问题,并且很可能是错误的原因(,也不需要像这样一遍又一遍地重新计算原始数组中的项目:
for(i=0;i<n;i++)
{
h[i]=count(arr,arr+n,arr[i]);
}
如果您有 1000 个号码,您将调用此计数循环 1000 次。 这是非常低效的。
至于您的实现,您将第一个副本的索引存储在哪里? 我没有看到它,除非它隐藏在你用这个flag
变量进行的所有操作后面。 无论你在做什么,都是错误的。
下面是一个实现,使用您的测试数据和我之前介绍的大纲:
#include <unordered_map>
#include <iostream>
#include <algorithm>
#include <climits>
int main()
{
std::unordered_map<int, int> numbers;
int test[] = {1, 5, 3, 4, 2, 4, 5};
// Set minimum index to a large value
int minIndex = std::numeric_limits<int>::max();
for (size_t i = 0; i < std::size(test); ++i )
{
// check if item is found
auto iter = numbers.find(test[i]);
if ( iter == numbers.end())
// not found, so add item and position
numbers.insert({test[i], i});
else
// set the minimum index to the found position and exit the loop
minIndex = std::min(minIndex, iter->second);
}
if ( minIndex == std::numeric_limits<int>::max())
std::cout << -1;
else
std::cout << minIndex;
}
输出:
1
这实际上具有O(n)
运行时,而不是您编写的内容,由于计数循环效率低下而O(n^2)
。
尽管有问题,但这行代码
int arr[n];
不允许C++即使您的本地 IDE 没有给出任何错误,我认为您的在线判断会给出运行时错误。
由于C++中的数组必须是静态分配的,这意味着您需要在运行代码之前知道数组的元素数。
相关文章:
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 如何仅读取文本文件中的第一个值
- 在C++中,如何在第一个"system()"结束后执行第二个"system()"?
- 查找不在标准中的第一个值::设置<int>最小-最大值
- C++:忽略第一个 cin.ignore 之后的输入
- 在C++中打印多个矢量的第一个值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- C++第一个cout将不会打印
- 我们可以在第一个else-if条件结束后使用另一个else-if条件吗
- OpenGL:第二个VBO破坏了第一个VBO
- 为什么第一个Dynamic_cast没有投射到基类?
- OpenGL 2D游戏只绘制第二个精灵纹理而不是第一个
- C++ 为什么程序只读取第一个值
- 在我的第一个C++程序中需要一些帮助(简单)
- 将顶部堆栈元素传输到第二个堆栈的第一个
- 获取不等于特定值的向量的第一个N元素
- 如何将std ::映射的第一个N元素复制到另一个地图
- 如何在C中获取char阵列的第一个X元素?提升效果是否有改进的方法