-
Notifications
You must be signed in to change notification settings - Fork 0
/
374.猜数字大小.ts
65 lines (54 loc) · 1.3 KB
/
374.猜数字大小.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
* @lc app=leetcode.cn id=374 lang=typescript
*
* [374] 猜数字大小
*/
// @lc code=start
/**
* Forward declaration of guess API.
* @param {number} num your guess
* @return -1 if num is higher than the picked number
* 1 if num is lower than the picked number
* otherwise return 0
* var guess = function(num) {}
*/
// function guessNumber(n: number): number {
// // 二分搜索
// let low = 1 // 最小范围
// let high = n // 最大范围
// // 循环
// while (low <= high) {
// // 中间值
// let mid = Math.floor((low + high) / 2)
// // 调用 guess 取 猜测的值
// let res = guess(mid)
// // 判断
// if (res === 0) {
// return mid
// } else if (res === 1) {
// // 猜大了 -> 二分
// low = mid + 1
// } else {
// // 猜小了 -> 二分
// high = mid - 1
// }
// }
// };
// 二分 - 递归
function guessNumber(n: number): number {
const rec = (low, high) => {
if (low > high) return
// 中间值
const mid = Math.floor((low + high) / 2)
const res = guess(mid)
if (res === 0) {
return mid
} else if (res === 1) {
return rec(mid + 1, high)
} else {
return rec(low, mid - 1)
}
}
return rec(1, n)
};
// @lc code=end