leetcode思路总结反思(bfs篇)
278. First Bad Version
最普通的二分查找:
class Solution {
public:
int firstBadVersion(int n) {
int lb=-1;
int ub=n+1;
while((ub-lb)>1)
{
int mid = (ub+lb)/2;
if(isBadVersion(mid))
ub=mid;
else
lb=mid;
}
return ub;
}
};
但是依然存在问题。。。
Line 11: Char 26: runtime error: signed integer overflow: 2126753391 + 1063376695 cannot be represented in type 'int' (solution.cpp)
lb和ub相加可能会导致int型整数溢出。所以需要改成long long,还要注意的一个问题是int ub=n+1;这一段中的n+1已经导致int溢出,所以需要将n+1改成n。
正确代码:
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
long long lb=-1;
long long ub=n;
while((ub-lb)>1)
{
long long mid = (ub+lb)/2;
if(isBadVersion(mid))
ub=mid;
else
lb=mid;
}
return ub;
}
};