Why my binary search get time limit exceed error


  • 0
    B

    Here is my JAVA solution, but get time limit exceed error

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

  • 0
    B

    i find that the begin+end will overflow and turn out to be a negative number, when input n is very big. So I change start = begin + (end - begin)/2.


  • 2
    B

    @bargitta The test cases include the MAX_Integer 2147483647, which means 2147483647 + 1 will turn out to be a negative value. Thus I should not use end = n + 1 or begin+end.

    Here is the right one

     int begin = 1;
            int end = n;
            int start;
            while(true){
                start = begin + (end - begin) / 2;
                int result = guess(start);
                if(result == 0) return start;
                if(result < 0) end = start - 1;
                else begin = start + 1;
            }
    
    

  • 0
    J

    @bargitta That seems to be the correct reason. We should use (max-min)/2+min from now on to evade the possible problem.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.