[Swift]LeetCode374. 猜数字大小 | Guess Number Higher or Lower
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9769494.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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 == n {return n} 4 var left:Int = 1 5 var right:Int = n 6 while(left < right) 7 { 8 var mid = left + (right - left)/2 9 if pick == mid 10 { 11 return mid 12 } 13 else if pick < mid 14 { 15 right = mid 16 } 17 else 18 { 19 left = mid 20 } 21 } 22 return -1 23 } 24 }
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 };