示例 1:
输入:n = 10, pick = 6
输出:6
示例 2:
输入:n = 1, pick = 1
输出:1
示例 3:
输入:n = 2, pick = 1
输出:1
示例 4:
输入:n = 2, pick = 2
输出:2
package BinarySearch;
public class p374_GuessTheSizeOfTheNumber {
public static void main(String[] args) {
int res = guessNumber(10);
System.out.println("res = " + res);
}
public static int guessNumber(int n) {
int left = 1;
int right = n;
while (left <= right) {
int mid = left + (right - left) / 2;
int pick = guess(mid);
if (pick == 0) {
return mid;
} else if (pick == -1) {
right = mid - 1;
} else if (pick == 1) {
left = mid + 1;
}
}
return 0;
}
public static int guess(int num) {
int pick = 6;
if (num == pick) {
return 0;
} else if (num < pick) {
return 1;
} else {
return -1;
}
}
}
#include
int guess(int num)
{
int pick = 6;
if (num == pick)
{
return 0;
}
else if (num < pick)
{
return 1;
}
else
{
return -1;
}
}
int guessNumber(int n)
{
int left = 1;
int right = n;
while (left <= right)
{
int mid = left + (right - left) / 2;
int pick = guess(mid);
if (pick == 0)
{
return mid;
}
else if (pick == 1)
{
left = mid + 1;
}
else if (pick == -1)
{
right = mid - 1;
}
}
return 0;
}
/*主函数省略*/
Java语言版
C语言版