题解 | #查找#二分

查找

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

#include <cstdio>
#include <algorithm>
using namespace std;
int arr[100];

/**
    n是数组长度
    key为要找的值
*/
bool binarySearch(int n, int key) {
    //找到了返回true
    //找不到返回false
    int left = 0;
    int right = n - 1;
    while (left <= right) {
        int mid = (left + right) / 2;
        if (arr[mid] == key) {
            return true;
        }
        if (arr[mid] < key) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return false;
}

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 key;
            scanf("%d", &key);
            if (binarySearch(n, key)) {
                printf("YES\n");
            } else {
                printf("NO\n");
            }
        }
    }
}

全部评论

相关推荐

11-15 19:28
已编辑
蚌埠坦克学院 硬件开发
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务