/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
int first=1;
int last=n;
int mid=(first+last)/2;
int temp=getPosition(mid);
while(true){
switch(temp){
case 0:
return n;
//break;
case 1:
last=mid-1;
mid=(first+last)/2;
temp=getPosition(mid);
break;
case -1:
first=mid+1;
mid=(first+last)/2;
temp=getPosition(mid);
break;
}
}
}
private int getPosition(int n){//-1 means before ,0 means is,1 means after
if(isBadVersion(n)==false){
return -1;
}else if(n==1){
return 0;
}else if(isBadVersion(n-1)==true){
return 1;
}else{
return 0;
}
}
/*public boolean isFirst(int n){
if(isBadVersion(n)==true){
if(n==1){
return true;
}else if(isBadVersion(n-1)==false){
return true;
}
}
return false;
}
public boolean isBefore(int n ){
if(isBadVersion(n)==false){
return true;
}
return false;
}
public boolean isAfter(int n){
if(isBadVersion(n)==true&&isBadVersion(n-1)==true){
return true;
}
return false;
}*/
}
第二套方案
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
int first=1;
int last=n;
int mid=(first+last)/2;
//int temp=getPosition(mid);
if(isBadVersion(1)==true){
return 1;
}
while(true){
if(first+1==last){
return last;
}
if(isBadVersion(mid)==true){
last=mid;
mid=(first+last)/2;
}else{
first=mid;
mid=(first+last)/2;
}
}
}
最后通过了的版本
Solution{
public int firstBadVersion(int n) {
int first=1;
int last=n;
int mid;
//int mid=(first+last)/2;
//int temp=getPosition(mid);
if(isBadVersion(1)==true){
return 1;
}
while(true){
if(first+1==last){
return last;
}
mid=first+(last-first)/2;
if(isBadVersion(mid)==true){
last=mid;
// mid=(first+last)/2;
}else{
first=mid;
}
}
}
}
重点来了
求一个两个数的中值的语句
mid=(first+last)/2;(超时)
mid=first+(last-first)/2;(通过)
从直观上来看前者比后者甚至少了一个加法的运算。但是又是什么原因呢?
傻乎乎地在百度知道和知乎上面问了一下,因为前者加法使得整形溢出。效果就是加法反而使得内存中的数仅剩下溢出以后剩余的数了。使得永远达不到循环结束条件。
2^32=4294967296.