1.问题描述
考虑元素唯一性问题:给出一个整数集合,假定这些整数存储在数组A[1…n]中,确定它们中是否存在两个相等的元素。请设计出一个有效算法来解决这个问题,你的算法的时间复杂性是多少?
2. 具体要求
输入:输入的第一行是一个正整数m,表示测试例个数。接下来几行是m个测试例的数据,每个测试例的数据由两行组成,其中第一行为一个正整数n (n<=500),表示整数序列的长度,第二行给出整数序列,整数之间用一个空格隔开。
输出:对于每个测试例输出一行,若该组测试例存在两个相等的元素则输出Yes,否则,输出No。每个测试例的输出数据用一行表示。
3. 测试数据
输入:3
10
9 71 25 64 38 52 5 31 19 45
16
26 35 17 92 53 24 6 57 21 12 34 2 17 86 75 33
20
15 87 32 7 84 35 26 45 78 96 52 22 37 65 9 43 21 3 33 91
输出:No
Yes
No
4. 设计与实现的提示
算法最坏情况和平均情况的时间复杂性是衡量算法优劣的重要指标,算法设计要求尽可能设计比较高效的算法。
#include "project.h"
struct testCase
{
int testLenth;
int* element;
};
int main()
{
int testCount = 0;
cout<<"请输入测试用例的个数:";
cin>>testCount;
cout<<endl;
testCase* cases = new testCase[testCount];
for (int i=0; i<testCount; i++)
{
int testLenth = 0;
cout<<"请输入第"<<i+1<<"测试用例的长度:";
cin>>cases[i].testLenth;
cases[i].element = new int[cases[i].testLenth];
for (int j=0; j<cases[i].testLenth; j++)
{
cout<<"请输入第"<<j<<"个元素:";
cin>>cases[i].element[j];
}
cout<<endl;
}
//开始测试
for (i=0; i<testCount; i++)
{
bool isSame = false;
//检测第I个测试用例是否有相同的元素
for (int j=0; j<cases[i].testLenth-1; j++)
{
for (int k=j+1; k<cases[i].testLenth; k++)
{
if (cases[i].element[j] == cases[i].element[k])
{
isSame = true;
break;
}
}
//检查是否有相同的元素
if (isSame)
{
cout<<"yes"<<endl;
break;
}
}
if (!isSame)
{
cout<<"no"<<endl;
}
}
//释放内存
for (i=0; i<testCount; i++)
{
delete cases[i].element;
}
delete cases;
cin.get();
cin.get();
return 0;
}