我已经给出了一个数组,我需要查找数组中是否存在重复元素?(我必须接受用户的输入。(
这是我的第一个代码,它给出了一些测试用例的错误答案:
#include<bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
unordered_map<int,int> mp;
int temp=1;
for(int i=0,i<n;i++)
{
int x; cin>>x;
if(mp.find(x)!=mp.end())
{
temp=-1; break;
}
mp[x]++;
}
if(temp==-1) cout<<"YES"<<endl; //if duplicate present
else cout<<"NO"<<endl;
mp.clear();
}
return 0;
}
这段代码在所有测试用例上都能完美运行:
#include<bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
unordered_map<int,int> mp;
int temp=1;
for(int i=0,i<n;i++)
{
int x;
cin>>x;
mp[x]++;
}
if(mp.size()<n) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
mp.clear();
}
return 0;
}
背后的原因是什么?
您在第一个代码中使用了break;
,但在第二个代码中没有使用。
使用break;
将阻止代码读取测试用例的一部分,并将其视为下一个文本用例,这将导致错误答案。
例如,使用此输入
2
5 5 5 1 2 3
2 2 2
您的第一个代码将打印
YES
NO
而正确的输出是
YES
YES
为防止出现这种情况,应移除break;
。