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 到 n 选择一个数字。 你需要猜我选择了哪个数字。
每次你猜错了,我会告诉你这个数字是大了还是小了。
你调用一个预先定义好的接口
guess(int num)
,它会返回 3 个可能的结果(-1
,1
或 0
):
-1 : 我的数字比较小 1 : 我的数字比较大 0 : 恭喜!你猜对了!
示例 :
输入: n = 10, pick = 6 输出: 6
8ms
1 class Solution { 2 func guessNumber(_ n: Int, _ pick: Int) -> Int { 3 if pick == 0 || pick == n {return n} 4 var left:Int = 1 5 var right:Int = n 6 var mid:Int = 0 7 while(left < right) 8 { 9 var mid = left + (right - left)/2 10 if pick == mid 11 { 12 return mid 13 } 14 else if pick < mid 15 { 16 right = mid 17 } 18 else 19 { 20 left = mid 21 } 22 } 23 return mid 24 } 25 }
C++版本:
1 // Forward declaration of guess API. 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 6 class Solution { 7 public: 8 int guessNumber(int n) { 9 int low=1; 10 while(low<=n){ 11 int mid=low+(n-low)/2; 12 int res=guess(mid); 13 if(res==0) return mid; 14 else if(res==-1) n=mid-1; 15 else low=mid+1; 16 } 17 return -1; 18 } 19 };
原文地址:https://www.cnblogs.com/strengthen/p/9769494.html
时间: 2024-10-08 07:43:40