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 will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API int guess(int num), which returns three possible results:
- -1: Your guess is higher than the number I picked (i.e. num > pick).
- 1: Your guess is lower than the number I picked (i.e. num < pick).
- 0: your guess is equal to the number I picked (i.e. num == pick).
Return the number that I picked.
Example 1:
Input: n = 10, pick = 6
Output: 6
Example 2:
Input: n = 1, pick = 1
Output: 1
Example 3:
Input: n = 2, pick = 1
Output: 1
Constraints:
- 1 <= n <= 231 - 1
- 1 <= pick <= n
Initial: Using the Switch and Int Division
- Takes far more time than if and if-else statements.
public class Solution extends GuessGame {
public int guessNumber(int n) {
int left= 0;
int middle = n/2;
int right = n;
while (left <= right) {
middle = left + (right - left)/2;
System.out.println(middle);
switch(guess(middle)){
case -1:
right = middle - 1;
break;
case 1:
left = middle +1;
break;
default:
return middle;
}
}
return middle;
}
}
Modified Version:
public class Solution extends GuessGame {
public int guessNumber(int n) {
int left= 0;
int right = n;
int middle = (int)((long)left + ((long)right - (long)left)/2);
while (left <= right) {
int compare = guess(middle);
if (compare == 0){
return middle;
} else if (guess(right)==0){
return right;
} else if (guess(left)==0){
return left;
} else if (compare == -1){
right = middle - 1;
} else {
left = middle + 1;
}
middle = (int)((long)left + ((long)right - (long)left)/2);
}
return middle;
}
}
'Algorithms and Data Structures > Coding Practices' 카테고리의 다른 글
LeetCode 852. Peak Index in a Mountain Array (0) | 2022.06.08 |
---|---|
LeetCode 35. Search Insert Position (0) | 2022.06.07 |
LeetCode 704. Binary Search (0) | 2022.06.03 |
CCI 4.3 List of Depths (0) | 2022.06.02 |
CCI 4.1 Route Between Nodes (0) | 2022.05.31 |