相等元素问题

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值