c++查找数组中重复的数字

如题所述

#include <iostream>
#include <vector>
#include <map>
using namespace std;

int main()
{
int nCount = 0;
cin >> nCount;
vector<int>  vecRepeat;
map<int, int> mapAll;
int nTmpData = 0;
for (int i = 0; i < nCount; i++)
{
cin >> nTmpData;
map<int, int>::iterator it = mapAll.find(nTmpData);
if (mapAll.end() == it)
{
mapAll.insert(make_pair(nTmpData, 1));
}
else
{
if (it->second == 1)
{
vecRepeat.push_back(nTmpData);
}
it->second += 1;
}
}

if (vecRepeat.size() > 0)
{
for (int j = 0; j < vecRepeat.size(); j++)
{
if (0 != j)
{
cout << ' ';
}
cout << vecRepeat[j];
}
}
else
{
cout << "None";
}
cout << endl;
return 0;
}


朋友,请【采纳答案】,您的采纳是我答题的动力,如果没有明白,请追问。谢谢。

追问

您还能在写的简单点吗 有的我都没有看到过,越简单越好哒

追答#include <iostream>
using namespace std;

int main()
{
int nCount = 0;
cin >> nCount;
int* arrData = new int[nCount]; // 存放所有数据
int nTmpData = 0;
bool bHadRepeat = false;
for (int i = 0; i < nCount; i++)
{
cin >> nTmpData;
arrData[i] = nTmpData;
int nRepeatCount = 0; // 重复数据个数
for (int j = 0; j < i; j++)
{
if (arrData[j] == nTmpData)
{
nRepeatCount++;
}
}
if (nRepeatCount == 1)
// 说明有重复数据,且前面只输入了一次
{
if (true == bHadRepeat)
{
    cout << " ";
// 前面已经输出了重复数据,
// 后面再输出重复数据就加空格
}
cout << nTmpData;
bHadRepeat = true;
}
}

if (false == bHadRepeat)
{
cout << "None";
}
cout << endl;
return 0;
}


// 这个可以看懂了吧。

温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网