在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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 -1 : My number is lower 1 : My number is higher 0 : Congrats! You got it! Example: n = 10, I pick 6. Return 6. 我们正在玩一个猜数字游戏。 游戏规则如下: -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 };
|
请发表评论