《算导》练习题 2.3-7

本文介绍了一种用于查找数组中是否存在两个元素之和等于特定值x的算法。该算法首先对数组进行排序,然后使用二分查找及lower_bound方法确定目标值是否存在。通过这种方式实现了高效的查找过程。

题目:

设计算法:查找集合 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


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值