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

Leetcode 704 will fail, need to check boundary #12

Open
hsinanchen2007 opened this issue Jul 27, 2022 · 2 comments
Open

Leetcode 704 will fail, need to check boundary #12

hsinanchen2007 opened this issue Jul 27, 2022 · 2 comments

Comments

@hsinanchen2007
Copy link

class Solution {
public:
int search(vector& A, int target) {
int L = 0, R = A.size();
while (L <= R) {
int M = (L + R) / 2;
if (A[M] == target) return M;
if (A[M] < target && A.size() != M + 1) L = M + 1;
else R = M - 1;
}
return -1;
}
};

@lzl124631x
Copy link
Owner

@hsinanchen2007 not needed. A[M] won't go out of bound. Even if it will, you should check M + 1 != A.size() before accessing A[M]...

@hsinanchen2007
Copy link
Author

Thanks for reply. Yes, I know in general it won't fail, but when I review different solutions at that day, there is a weird testcase and that will fail at that day. That's why I added that condition to pass it. It seems like Leetcode already removed that testcase and now it's working fine again. Again, really appreciate your solutions here! If possible, you may try to add comments and explanation to help more people. :-)

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