You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

二分查找求元素首尾位置代码仅通过67/88测试用例,求问题排查

问题分析与修复

你的代码核心问题出在数组长度的传递错误,导致部分元素被排除在二分查找范围之外,具体问题和修复方案如下:

1. 数组长度传递错误

在searchRange函数中,你将n赋值为nums.size()-1(这是数组最后一个元素的索引),但FirstOccurence和LastOccurence函数的参数n被当作数组长度使用,进而在函数内计算high = n - 1,直接导致查找范围的上限被错误缩小一位。

比如:

  • 数组长度为5(索引0-4)时,n被设为4,函数内high = 4-1=3,漏掉了索引4的元素;
  • 数组长度为1时,n=0,函数内high=-1,循环直接跳过,永远找不到目标元素。

修复方法:
将searchRange中的n改为数组的实际长度:

int n = nums.size();

2. 额外优化(非错误但建议修改)

你的FirstOccurence和LastOccurence函数中,数组参数采用传值传递(vector<int> arr),会导致数组被拷贝,降低效率。建议改为const引用传递:

int FirstOccurence(const vector<int>& arr, int n, int x)
int LastOccurence(const vector<int>& arr, int n, int x)

修复后的完整代码

class Solution {
public:
int FirstOccurence(const vector<int>& arr, int n, int x) {
    int low = 0, high = n - 1;
    int ans = -1;

    while (low <= high) {
        int mid = (low + high) / 2;
        if (arr[mid] == x) {
            ans = mid;
            high = mid - 1;
        } else if (arr[mid] < x) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return ans;
}

int LastOccurence(const vector<int>& arr, int n, int x) {
    int low = 0, high = n - 1;
    int ans = -1;

    while (low <= high) {
        int mid = (low + high) / 2;
        if (arr[mid] == x) {
            ans = mid;
            low = mid + 1;
        } else if (arr[mid] > x) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }
    return ans;
}

vector<int> searchRange(vector<int>& nums, int target) {
    int n = nums.size();
    int a = FirstOccurence(nums, n, target);
    int b = LastOccurence(nums, n, target);
    return {a, b};
}
};

内容的提问来源于stack exchange,提问作者Raghav Khandelwal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 09:40:25