6 条题解

  • 0
    @ 2024-4-20 12:33:48

    #include <iostream> #include <vector> using namespace std;

    pair<int, int> findRange(const vector<int>& arr, int target) { int n = arr.size(); int left = -1, right = -1;

    // 寻找起始位置
    int low = 0, high = n - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] < target) {
            low = mid + 1;
        } else if (arr[mid] > target) {
            high = mid - 1;
        } else {
            left = mid;
            high = mid - 1; // 继续寻找左边界
        }
    }
    
    // 寻找终止位置
    low = 0, high = n - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] < target) {
            low = mid + 1;
        } else if (arr[mid] > target) {
            high = mid - 1;
        } else {
            right = mid;
            low = mid + 1; // 继续寻找右边界
        }
    }
    
    return {left, right};
    

    }

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

    vector<int> arr(n);
    for (int i = 0; i < n; ++i) {
        cin >> arr[i];
    }
    
    for (int i = 0; i < q; ++i) {
        int target;
        cin >> target;
        pair<int, int> result = findRange(arr, target);
        cout << result.first << " " << result.second << endl;
    }
    
    return 0;
    

    }

    信息

    ID
    88
    时间
    1000ms
    内存
    256MiB
    难度
    7
    标签
    递交数
    655
    已通过
    149
    上传者