题解 | #查找#

查找

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

#include "cstdio"
#include "algorithm"

using namespace std;

// 对升序数组二分查找
bool binary_search(int n, int x, int arr[]) {
    int left = 0, right = n - 1;
    while (left <= right) {
        int mid = right + (left - right) / 2;
        if (arr[mid] == x) {
            return true;
        } else if (arr[mid] > x) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return false;
}

/**
 *
 * @return
 */
int main() {
    int n, m;
    scanf("%d", &n);
    int arr[n + 1];
    for (int i = 0; i < n; ++i) {
        scanf("%d", &arr[i]);
    }
    sort(arr, arr + n);
    scanf("%d", &m);
    int x;
    for (int i = 0; i < m; ++i) {
        scanf("%d", &x);
        if (binary_search(n, x, arr)) {
            printf("YES\n");
        } else {
            printf("NO\n");
        }
    }
    return 0;
}

全部评论

相关推荐

想去夏威夷的小哥哥在度假:5和6才是重点
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务