這個挺直接的,也被李特標(biāo)了EASY.
就是在1~n里面找第一個出錯點(diǎn)玻孟。其實(shí)就是搜一個數(shù)字i(同時用isBadVersion(i))檢查這個數(shù)字是否報錯蜈漓。那搜index的活酬凳,直接binary search就好了。
注意特別條件:
!isBadVersion(i) && isBadVersion(i+1)
一定要找出這個i+1红柱,就是第一個出錯點(diǎn)承匣。
還有就是:很可能start == end了呀,如果還沒有完結(jié)锤悄,那么最終的那個情況必然是start==end==mid, 然后既然mid之前沒找到錯韧骗,那么try 一try isBadVersion(mid) 就好了。
/*
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
*/
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
if (n <= 1) {
return isBadVersion(n) ? n : -1;
}
int start = 1;
int end = n;
int mid = start + (end - start) / 2;
while(start < end) {
mid = start + (end - start) / 2;
if (!isBadVersion(mid) && isBadVersion(mid + 1)) {
return mid + 1;
} else if (!isBadVersion(mid)){
start = mid;
} else {
end = mid;
}
}
return isBadVersion(mid) ? mid : -1;
}
}