c++ binary search


  • 3
    A

    Declare res to equal the API call to only have 1 API call/iteration

    class Solution {
    public:
        int guessNumber(int n) {
            //simple binary search : low = 1; high = n
            int low = 1;
            while(low <= n){
                int mid = low + (n-low) / 2;
                int res = guess(mid);
                if(res == 0)
                    return mid;
                else if(res == -1)
                    n = mid - 1;
                else
                    low = mid + 1;
            }
            return -1;
        }
    };

Log in to reply
 

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