51Nod 2063 二分查找 c/c++题解

本文介绍了一个二分查找算法的应用实例,通过输入已排序的整数数组和查询整数,使用二分查找判断查询整数是否存在于数组中。文章提供了两种实现方法,一种是手动实现的二分查找,另一种是利用C/C++的内置函数lower_bound()。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

输入一个整数n和n个整数,保证这n个整数已经按照从小到大进行排序。
然后输入一个整数q(q <= 100000)代表q次查询。接下来q行,每行含有一个整数m,代表一次查询。对于每次查询,使用二分查找判断m是否在之前输入的n个整数中出现过。如果出现,输出一行"Yes",否则输出"No"。
输入
第一行:一个整数n(n <= 100000)。
接下来n行,每行一个整数ai(1 <= ai <= 10^9)。
接下来一行,一个整数q。
接下来q行,每行输入一个整数x(1 <= x <= 10^9)。
输出
q行字符串,每行为"Yes"或"No"。
输入样例
5
1
3
4
5
7
3
4
5
0
输出样例
Yes
Yes
No

题解:

这题不解释了,直接手写一个二分即可,不过其实还可以用c/c++内置的函数lower_bound()来求。

代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;

typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll  INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e5+5;
int n; int a[MAX];
int q,x;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    while(cin >> n)
    {
        for(int i = 0; i < n; i++)
        {
            cin >> a[i];
        }
        cin >> q;
        for(int i = 1; i <= q; i++)
        {
            cin >> x;
            /* 方法1
            int l = 0;
            int r = n-1;
            while(l <= r)
            {
                int mid = (l+r)/2;
                if(a[mid] == x)
                {
                    break;
                }
                else if(a[mid] > x)
                {
                    r = mid - 1;
                }
                else if(a[mid] < x)
                {
                    l = mid + 1;
                }
            }
            if(l <= r)
            {
                cout << "Yes" << endl;
            }
            else
            {
                cout << "No" << endl;
            }
            */
            
            /* 方法2
            // 函数lower_bound()可以返回a数组中<=x的第一个数的位置
            int * p = lower_bound(a,a+n,x);
            if(*p == x)
            {
                cout << "Yes" << endl;
            }
            else
            {
                cout << "No" << endl;
            }
            */
        }
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值