374. Guess Number Higher or Lower Description 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......
解法: // Forward declaration of guess API.// @param num, your guess// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0intguess(intnum);classSolution{public:intguessNumber(intn){intl =1, r = n;intmid =0;while(l <= r){ mid = l + (r - l)/...
02 第一种解法 暴力解法,直接使用for循环,依次调用guess(int num)方法,直到猜对了为止。但是此解法超时。 此解法时间复杂度是O(n),空间复杂度是O(1)。 publicintguessNumber(intn){for(inti=1; i<n; i++) {if(guess(i) ==0) {returni; } }returnn; } 03 第二种解法 使用二分查找法来判断,在...
374. Guess Number Higher or Lower We are playing the Guess Game. The game is as follows: I pick a number from1ton. 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...
public class Solution : GuessGame { public int GuessNumber(int n) { int left = 1, right = n; while (left < right) { // 循环直至区间左右端点相同 int mid = left + (right - left) / 2; // 防止计算时溢出 if (guess(mid) <= 0) { right = mid; // 答案在区间 [left, mid] ...
picked number * 1 if num is lower than the picked number * otherwise return 0 * func guess(num int) int; */ func guessNumber(n int) int { // 二分区间为 [1, n] l, r := 1, n // 当二分区间不为空时,继续处理 for l <= r { // 区间中点作为猜测的数,调用 guess 进行判断。
Can you solve this real interview question? Guess Number Higher or Lower II - We are playing the Guessing Game. The game will work as follows: 1. I pick a number between 1 and n. 2. You guess a number. 3. If you guess the right number, you win the ga
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 I picked is higher or lower. However, when you guess a particular number x, and you guess wrong, you pay $x. You win the game when you guess ...
-1 : My number is lower 1 : My number is higher 0 : Congrats! You got it! 1. 2. 3. Example: AI检测代码解析 n = 10, I pick 6. Return 6. 1. 2. 3. 题目大意 从1~n中取了一个数字,现在给出了guess()函数,要你猜这个数字是多少。
374. Guess Number Higher or Lower的拓展,这题每猜一次要给一次和猜的数字相等的钱,求出最少多少钱可以保证猜出。 解法:根据题目中的提示,这道题需要用到Minimax极小化极大算法。 Python: class Solution(object): def getMoneyAmount(self, n):