题目:
设计算法:查找集合 S 中是否存在两个其和等于 x 的元素。
解析:
先排序(sort),对每个数组元素(s[i]),在数组中二分查找它的补元素(x-s[i]):利用<algorithm>中的binary_search(起始位置,终止位置,目标值)和lower_bound(起始位置,终止位置,目标值)即可快速查找。最后输出相应结果即可。
附上函数讲解:
STL之二分查找(binary_search(),lower_bound(),upper_bound() )
代码:
#include<cstdio>
#include<algorithm>
#define maxn 10007
using namespace std;
int a[maxn];
bool check(int s[],int n,int x)
{
sort(s,s+n);
for(int i = 0;i < n;i++)
{
int v = x - s[i];
if(binary_search(s,s+n,v)&&lower_bound(s,s+n,v) != s+i)
{
return true;
}
}
return false;
}
int main()
{
int n;
while(~scanf("%d",&n))
{
for(int i = 0; i < n; i++)
{
scanf("%d",&a[i]);
}
int m,x;
scanf("%d",&m);
while(m--)
{
scanf("%d",&x);
if(check(a,n,x))
{
printf("Yes ");
}
else
{
printf("No ");
}
}
}
}
测试数据:
5
1 2 3 4 5
12
0 1 2 3 4 5 6 7 8 9 10 11
测试结果:
No No No Yes Yes Yes Yes Yes Yes Yes No No
本文介绍了一种用于查找数组中是否存在两个元素之和等于特定值x的算法。该算法首先对数组进行排序,然后使用二分查找及lower_bound方法确定目标值是否存在。通过这种方式实现了高效的查找过程。
1292

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



