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

LeetCode猜数字问题二分搜索代码超时原因排查求助

代码超时原因分析与修复

你的代码超时的核心问题是找到目标数字后没有立刻终止循环:
当guess(mid) == 0时,你仅将pick赋值为mid,但循环条件start<=end仍然成立,循环会继续执行直到start大于end才停止。这期间做了大量无意义的迭代,直接导致执行时间过长甚至超时。

修复后的代码

public class Solution extends GuessGame {
    public int guessNumber(int n) {
        int start = 1;
        int end = n;
        while (start <= end) {
            int mid = start + (end - start) / 2;
            int res = guess(mid);
            if (res == -1) {
                end = mid - 1;
            } else if (res == 1) {
                start = mid + 1;
            } else {
                // 找到目标值直接返回,终止循环
                return mid;
            }
        }
        // 理论上不会走到这里,题目保证存在目标值
        return -1;
    }
}

关键修复点

  1. 找到目标值(res == 0)时直接return mid,立刻终止循环,避免后续无效的循环迭代。
  2. 提前把guess(mid)的结果存到变量res里,避免重复调用guess方法(虽非超时主因,但能小幅优化性能)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:24:22