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] master from labuladong:master #87

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:master from labuladong:master
May 4, 2023
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
6 changes: 6 additions & 0 deletions 算法思维系列/二分查找详解.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ int binarySearch(int[] nums, int target) {
}
```

<visual slug='binary-search'/>

这段代码可以解决力扣第 704 题「二分查找」,但我们深入探讨一下其中的细节。

**1、为什么 while 循环的条件中是 <=,而不是 <**?
Expand Down Expand Up @@ -289,6 +291,8 @@ int left_bound(int[] nums, int target) {
}
```

<visual slug='mydata-left-bound'/>

这样就和第一种二分搜索算法统一了,都是两端都闭的「搜索区间」,而且最后返回的也是 `left` 变量的值。只要把住二分搜索的逻辑,两种形式大家看自己喜欢哪种记哪种吧。

### 三、寻找右侧边界的二分查找
Expand Down Expand Up @@ -387,6 +391,8 @@ int right_bound(int[] nums, int target) {
}
```

<visual slug='mydata-right-bound'/>

当然,由于 while 的结束条件为 `right == left - 1`,所以你把上述代码中的 `left - 1` 都改成 `right` 也没有问题,这样可能更有利于看出来这是在「搜索右侧边界」。

至此,搜索右侧边界的二分查找的两种写法也完成了,其实将「搜索区间」统一成两端都闭反而更容易记忆,你说是吧?
Expand Down

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