leetcode 374. Guess Number Higher or Lower 猜数游戏 + 二分查找

墨蓝 2022-06-07 02:47 228阅读 0赞

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’ll tell you whether the number is higher or lower.

You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):

-1 : My number is lower
1 : My number is higher
0 : Congrats! You got it!
Example:
n = 10, I pick 6.

Return 6.

最经典的猜数游戏。

代码如下:

  1. /* The guess API is defined in the parent class GuessGame.
  2. @param num, your guess
  3. @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
  4. int guess(int num); */
  5. public class Solution extends GuessGame
  6. {
  7. public int guessNumber(int n)
  8. {
  9. int beg=1 , end=n;
  10. while(beg<end)
  11. {
  12. int mid=(end-beg)/2 + beg;
  13. int res=guess(mid);
  14. if(res==0)
  15. return mid;
  16. else if(res==1)
  17. beg=mid+1;
  18. else
  19. end=mid-1;
  20. }
  21. return beg;
  22. }
  23. }

下面是C++的做法,

就是一个简单的二分查找

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <unordered_map>
  5. #include <set>
  6. #include <unordered_set>
  7. #include <queue>
  8. #include <stack>
  9. #include <string>
  10. #include <climits>
  11. #include <algorithm>
  12. #include <sstream>
  13. #include <functional>
  14. #include <bitset>
  15. #include <numeric>
  16. #include <cmath>
  17. #include <regex>
  18. using namespace std;
  19. // Forward declaration of guess API.
  20. // @param num, your guess
  21. // @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
  22. int guess(int num);
  23. class Solution
  24. {
  25. public:
  26. int guessNumber(int n)
  27. {
  28. int beg = 1, end = n;
  29. while (beg < end)
  30. {
  31. int mid = (end - beg) / 2 + beg;
  32. int res = guess(mid);
  33. if (res == 0)
  34. return mid;
  35. else if (res == 1)
  36. beg = mid + 1;
  37. else if(res==-1)
  38. end = mid - 1;
  39. }
  40. return beg;
  41. }
  42. };

发表评论

表情:
评论列表 (有 0 条评论,228人围观)

还没有评论,来说两句吧...

相关阅读