Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[pull] main from itcharge:main #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
pull merged 1 commit into AlgorithmAndLeetCode:main from itcharge:main
Jul 11, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions Solutions/0374. 猜数字大小.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,36 @@

## 题目大意

猜数字游戏。给定一个整数 n 和一个接口 `def guess(num: int) -> int:`,题目会从 1~n 中随机选取一个数 x。我们只能通过调用接口来判断自己猜测的数是否正确。要求返回题目选取的数字 x。
**描述**:猜数字游戏。给定一个整数 `n` 和一个接口 `def guess(num: int) -> int:`,题目会从 `1` ~ `n` 中随机选取一个数 `x`。我们只能通过调用接口来判断自己猜测的数是否正确。

**要求**:要求返回题目选取的数字 `x`。

**说明**:

- `def guess(num: int) -> int:` 返回值:
- $-1$:我选出的数字比你猜的数字小,即 $pick < num$;
- 1ドル$:我选出的数字比你猜的数字大 $pick > num$;
- 0ドル$:我选出的数字和你猜的数字一样。恭喜!你猜对了!$pick == num$。


**示例**:

```Python
输入 n = 10, pick = 6
输出 6
```

## 解题思路

利用两个指针 left、right。left 指向数字 1,right 指向数组 n。每次从中间开始调用接口猜测是否正确。
### 思路 1:二分查找

利用两个指针 `left`、`right`。`left` 指向数字 `1`,`right` 指向数字 `n`。每次从中间开始调用接口猜测是否正确。

- 如果猜测的数比选中的数大,则将 right 向左移,继续从中间调用接口猜测;
- 如果猜测的数比选中的数小,则将 left 向右移,继续从中间调用的接口猜测;
- 如果猜测的数比选中的数大,则将 `right` 向左移,令 `right = mid - 1`,继续从中间调用接口猜测;
- 如果猜测的数比选中的数小,则将 `left` 向右移,令 `left = mid + 1`,继续从中间调用的接口猜测;
- 如果猜测正确,则直接返回该数。

## 代码
### 思路 1:二分查找代码

```Python
class Solution:
Expand Down

AltStyle によって変換されたページ (->オリジナル) /