【问题标题】:time limit exceeded in binary search leetcode problem二分查找leetcode问题超出时间限制
【发布时间】:2022-08-24 14:57:59
【问题描述】:

https://leetcode.com/problems/guess-number-higher-or-lower/ 以上是问题的链接

public class Solution extends GuessGame {
public int guessNumber(int n) {
    int start=1;
    int end=n;
    int pick=0;
    while(start<=end){
        int mid=start+(end-start)/2;
        if(guess(mid)==-1){
            end=mid-1;
        }else if(guess(mid)==1){
            start=mid+1;
        }else if(guess(mid)==0) {
            pick=mid;
        }
    }
    return pick;
}

}

此代码需要 500 多毫秒才能执行 请提出为什么需要这么多时间

  • 因为一旦你猜对了,你就不会退出循环。我建议将return pick; 向上移动几行。

标签: java binary-search


【解决方案1】:

你为什么不简单地返回值一旦你得到(猜测(中)==0)? 在你的情况下,即使你的工作完成后你也会继续迭代。所以你可以猜到为什么它需要更多的时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多