1ms Java Binary Search Solution


  • 0
    K

    Iterative inclusive binary search solution for this problem. The time complexity is O(logn).

        public int guessNumber(int n) {
            int left = 1, right = n;
            while (left <= right) {
                int mid = left + (right - left) / 2;
                int ret = guess(mid);
                if (ret == 0) {
                    return mid; 
                } else if (ret < 0) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            }
            
            return -1;
        }
    

Log in to reply
 

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