U521105 查找边界值求解

灌水区

cjy_lsmdsb @ 2025-01-10 20:33:10

#include <iostream>

int binarySearch(int a[], int n, int x) {
    int left = 0;
    int right = n - 1;

    while (left <= right) {
        int mid = left + (right - left) / 2;

        if (a[mid] >= x) {
            right = mid;
        } else {
            left = mid + 1;
        }
    }

    if (left < n && a[left] == x) {
        return 1;
    } else {
        return 0;
    }

    if (left >= n) {
        return n + 1;
    } else {
        return left + 1;
    }
}

int main() {
    int n, m;
    cin >> n >> m;

    int a[n];
    for (int i = 0; i < n; i++) {
        std::cin >> a[i];
    }

    for (int i = 0; i < m; i++) {
        int x;
        cin >> x;
        int result = binarySearch(a, n, x);
       cout << result <<endl;
    }

    return 0;
}

用的二分,但10分


by cjy_lsmdsb @ 2025-01-10 20:33:30

求代码


|