题解 | #查找#

查找

https://www.nowcoder.com/practice/d93db01c2ee44e8a9237d63842aca8aa

#include <iostream>
#include "cstdio"
#include "algorithm"
using namespace std;
bool BinarySearch(int arr[], int left, int right, int x) {
    int mid;
    while (left <= right) {
        mid = (left + right) / 2;
        if (arr[mid] == x)
            return true;
        if (arr[mid] > x) {
            right = mid - 1;
        } else
            left = mid + 1;

    }
    return false;
}
int main() {
    int n;
    scanf("%d", &n);
    int arr[n];
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    sort(arr, arr + n); ///二分查找需要有序数组

    int m;
    scanf("%d", &m);
    int integer[m];
    for (int i = 0; i < m; i++) {
        scanf("%d", integer + i);
    }
    for (int i = 0; i < m; i++) {
        if (BinarySearch(arr, 0, n - 1, integer[i]))
            printf("%s\n", "YES");
        else
            printf("%s\n", "NO");
    }



    return 0;
}

全部评论

相关推荐

努力学习的小绵羊:我反倒觉得这种挺好的,给不到我想要的就别浪费大家时间了
点赞 评论 收藏
分享
我见java多妩媚:大外包
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务