Skip to content
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

There may be overflow in the binary search function at page16 #5

Closed
woodpenker opened this issue Nov 28, 2020 · 1 comment
Closed

Comments

@woodpenker
Copy link

First I want to say this is an excellent job! Thank you for sharing this!
At page 16, for question 34. Find First and Last Position of Element in Sorted Array (Medium), the function lower_bound below
may have a bug:

int lower_bound(vector<int> &nums, int target) {
int l = 0, r = nums.size(), mid;
while (l < r) {
mid = (l + r) / 2; // Here, may be overflow when r = MAX_INT and l= MAX_INT/2
if (nums[mid] >= target) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}

mid = (l + r) / 2; This code may be overflow when r = MAX_INT and l= MAX_INT/2, you should use mid = (r-l)/2+l instead.

Also the same for the upper_bound function.

@changgyhub
Copy link
Owner

Thanks!

Honestly I really don't want to touch too much about edge cases like this. Will be updated in the next version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants