Skip to content

Commit 9b06af3

Browse files
committed
🎃(binary-search): 374. 猜数字大小 add java code
1 parent f725a97 commit 9b06af3

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

docs/algorithm/research/binary-search/README.md

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,10 @@ class Solution(object):
372372

373373
本质就是一个在 `1 ~ n` 范围内查找某个特定数的过程,用二分来做。
374374

375+
<!-- tabs:start -->
376+
377+
#### ** Python **
378+
375379
```python
376380
# The guess API is already defined for you.
377381
# @param num, your guess
@@ -399,4 +403,35 @@ class Solution(object):
399403
else:
400404
# 猜对了
401405
return mid
402-
```
406+
```
407+
408+
#### ** Java **
409+
410+
```java
411+
/* The guess API is defined in the parent class GuessGame.
412+
@param num, your guess
413+
@return -1 if my number is lower, 1 if my number is higher, otherwise return 0
414+
int guess(int num); */
415+
416+
public class Solution extends GuessGame {
417+
public int guessNumber(int n) {
418+
int start = 1;
419+
int end = n;
420+
while(start < end) {
421+
int mid = start + (end - start) / 2;
422+
int result = guess(mid);
423+
if (result == 0) {
424+
return mid;
425+
} else if (result == -1) {
426+
end = mid - 1;
427+
} else if (result == 1) {
428+
start = mid + 1;
429+
}
430+
}
431+
432+
return end;
433+
}
434+
}
435+
```
436+
437+
<!-- tabs:end -->

0 commit comments

Comments
 (0)