该题可以采用set,其可自动排序。遍历set,然后查找m-*it是否也在set中。
注意:为了解决出现多次的数,可以采用hash来记录各个数字的个数,如果*it乘以2等于m,且hash[*it]>=2,则满足条件。
AC代码:
#include<iostream>
#include<vector>
#include<map>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
#include<list>
#include<set>
#define inf 26*26*26*10+5
using namespace std;
set<int> s;
int hashh[505];
int main()
{
int n,m;
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++)
{
int d;
scanf("%d",&d);
hashh[d]++;
s.insert(d);
}
set<int>::iterator it;
int flag=0;
for( it=s.begin();it!=s.end();it++)
{
if(s.find(m-*it)!=s.end())
{
if(2*(*it)==m&&hashh[*it]<2)
{
continue;
}
printf("%d %d",*it,m-*it);
flag=1;
break;
}
}
if(flag==0)
{
printf("No Solution");
}
}
本文介绍了一种使用set和hash解决寻找整数数组中特定数对的问题。通过遍历set并检查目标值减去当前元素是否存在于set中来确定数对的存在性。特别地,当目标值的一半在set中出现时,需要确保该值至少出现了两次。
7900

被折叠的 条评论
为什么被折叠?



