374. Guess Number Higher or Lower
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.
Answer
class Solution:
def guessNumber(self, n: int) -> int:
low, high = 1, n
while low <= high:
mid = (low + high) // 2
result = guess(mid)
if result == -1:
high = mid ㅁ- 1
elif result == 1:
low = mid + 1
else:
return mid
How Binary Search Works
Precondition :
The input list or range must be sorted
Divide and Conquer :
Start with the entire search range
Calculate the middle point of the range.
Compare the target value with the middleelement.
Dicision:
If the target is smaller than the middlel element, eliminate the upper half of the range.
If the target is larger. eliminate the lower half.
If the target is equal to the middle element, return it.
So
in Each Loop
until low exceeds high:
- Calculate the middle point : mid = (low + high) // 2
- Check
If the value at mid is equal to the target, return mid
If the value at mid is greater thatn the target, move high to mid - 1
If the value at mid is less than the target, move low to mid + 1
'개발 공부 > Algorithm' 카테고리의 다른 글
[LeetCode] 60. Can Place Flowers (0) | 2025.01.05 |
---|---|
[LeetCode] 62. Unique Paths (1) | 2024.12.15 |
Permute Practice (0) | 2024.12.15 |
[LeetCode] 17. Letter Combinations of a Phone Number (2) | 2024.12.13 |
[LeetCode] 2390. Removing Stars From a String (0) | 2024.12.10 |