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

增加二分查找 mid 的取值方法说明和更新,避免极端情况下类型溢出 #35

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

Closed
zhanzengyu wants to merge 3 commits into Blankj:master from zhanzengyu:master
Closed
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
12 changes: 10 additions & 2 deletions note/035/README.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -44,17 +44,25 @@ Output: 0
```java
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0, right = nums.length - 1, mid = (right + left) >> 1;
int left = 0, right = nums.length - 1, mid = left + ((right - left) >> 1);
while (left <= right) {
if (target <= nums[mid]) right = mid - 1;
else left = mid + 1;
mid = (right + left) >> 1;
mid = left + ((right - left) >> 1);
}
return left;
}
}
```

**mid 说明:**
有两种处理方法:
1. mid = (left + right) >> 1
2. mid = left + ((right - left) >> 1)

在一般情况下两种都可以。

但是当 left 和 right 接近于 int 的最大值时,**(left + right)** 可能发生类型溢出,因此推荐用第二种方式。

## 结语

Expand Down

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