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

请求协助调试/重构二分查找代码(仅允许修改三行)

Hey there! Let's tackle this binary search code—there are a couple of critical issues that can cause infinite loops or integer overflow, and we can fix everything with exactly three line changes. Here's the breakdown:

First, let's spot the problems in the original code:

  • Integer Overflow: Calculating m = (l + r) / 2 can overflow when l and r are large positive integers (since their sum might exceed the maximum value of int).
  • Infinite Loop: When A[m] <= X, setting l = m can trap the loop in an infinite cycle. For example, if l=0 and r=1, m=0—if A[0] <= X, l stays 0, and the loop condition l < r never becomes false.
  • Incorrect Final Check: After the loop, l might point to a position just past the target value, so checking only A[l] can miss the actual target.

Here's the fixed code with exactly three modified lines (marked with comments):

int binaryS(int[] A, int X) {
    int N = A.length;
    if (N == 0) {
        return -1;
    }
    int l = 0;
    int r = N - 1;
    while (l < r) {
        // Modified line 1: Avoid integer overflow with safer midpoint calculation
        int m = l + (r - l) / 2; 
        if (A[m] > X) {
            r = m - 1;
        } else {
            // Modified line 2: Move left boundary forward to prevent infinite loops
            l = m + 1; 
        }
    }
    // Modified line 3: Check the correct position after loop convergence
    if (l > 0 && A[l-1] == X) { 
        return l-1;
    }
    return -1;
}

Why these changes work:

  1. The midpoint calculation l + (r - l)/2 avoids overflow because it only subtracts first, ensuring we never exceed the int range.
  2. Setting l = m + 1 when A[m] <= X ensures the left boundary always moves forward, breaking any potential infinite loops. The loop will eventually converge when l == r.
  3. After the loop, l will be either the first index where A[l] > X or equal to N (if all elements are <= X). Checking A[l-1] covers the case where the target was the last valid element we checked before the loop ended.

This fixed version handles edge cases like empty arrays, target values at the start/end of the array, duplicate values, and large arrays without overflow issues.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:11:02