euisblue
374. Guess Number Higher or Lower

https://leetcode.com/problems/guess-number-higher-or-lower/

Solved: 7m00s

Problem

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.

You call a pre-defined API int guess(int num), which returns three possible results:

  • -1: Your guess is higher than the number I picked (i.e. num > pick).
  • 1: Your guess is lower than the number I picked (i.e. num < pick).
  • 0: your guess is equal to the number I picked (i.e. num == pick).

Return the number that I picked.

Solution

1/** 2 * Forward declaration of guess API. 3 * @param num your guess 4 * @return -1 if num is lower than the guess number 5 * 1 if num is higher than the guess number 6 * otherwise return 0 7 * int guess(int num); 8 */ 9 10class Solution { 11public: 12 int bsearch(int b, int e) { 13 while(b <= e) { 14 int mid = b + (e-b)/2; 15 if(guess(mid) == 0) return mid; 16 if(guess(mid) == -1) e = mid-1; 17 if(guess(mid) == 1) b = mid+1; 18 } 19 return -1; 20 } 21 int guessNumber(int n) { 22 return bsearch(1, n); 23 } 24};

Time Complexity

  • Binary search havles every time - logN
  • O(logN)

Space Complexity

  • No extra storage was used.
  • O(1)