题解 | #查找#

查找

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

#include "cstdio"
#include "iostream"
#include "algorithm"
using namespace std;
int array[100];
bool BinarySearch(int n, int target) {
    int left = 0;
    int right = n - 1;
    while (left <= right) {
        int middle = (left + right) / 2;
        if (array[middle] < target) {
            left = middle + 1;
        } else if (target < array[middle]) {
            right = middle - 1;
        } else {
            return true;
        }
    }
    return false;
}
int main() {

    int n, m;
    while (scanf("%d", &n) != EOF) {
        for (int i = 0; i < n; ++i) {
            scanf("%d", &array[i]);
        }
        sort(array, array + n);
        scanf("%d", &m);
        for (int i = 0; i < m; ++i) {
            int target;
            scanf("%d", &target);
            if (BinarySearch(n, target)) {
                cout << "YES" << endl;
            } else {
                cout << "NO" << endl;
            }
        }
    }
    return 0;

}

全部评论

相关推荐

10-05 23:02
东北大学 Java
我说句实话啊:那时候看三个月培训班视频,随便做个项目背点八股,都能说3 40w是侮辱价
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务