题解 | #查找#

查找

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

#include <iostream>
#include <algorithm>
#include <cstdio>

using namespace std;

int arr[100];

int binary_search(int x, int n) {
    //找到返回true
    int left = 0;
    int right = n - 1;
    while (left <= right) {
        int mid = (left + right) / 2;
        if (arr[mid] == x) {
            return mid;
        } else if (arr[mid] > x) {
            //右边往左缩
            right = mid - 1;
            //最后边界情况,right可能与left相等,下次right可能变成left-1
        } else {
            left = mid + 1;
        }
    }
    return -1;
}

int main() {
    int n, m;
    while (scanf("%d", &n) != EOF) {
        for (int i = 0; i < n; i++) {
            scanf("%d", &arr[i]);
        }
        sort(arr, arr + n);

        scanf("%d", &m);

        for (int i = 0; i < m; i++) {
            int x;
            scanf("%d", &x);
            if (binary_search(x, n) != -1) {
                printf("YES\n");
            } else {
                printf("NO\n");
            }
        }
    }
    return 0;
}

全部评论

相关推荐

dongsheng66:如果想进大厂的话,在校经历没必要占这么大篇幅,可以把专业技能单独放一个专栏写,可以加个项目经历
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务