今日簡單題:https://leetcode-cn.com/problems/first-bad-version/
比較清晰的二分法,關(guān)注下while不要死循環(huán)即可。
另外吐槽一下題解,mid=head+(tail-head)/2; 那不就是mid=(head+tail)/2嗎?這個(gè)還更直觀,就是中位數(shù)。
貼下代碼:
/* 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 head = 1;
int tail = n;
int tmp = (head+tail)/2;
while(head < tail) {
// 如果tmp是壞版本,那第一個(gè)壞版本一定在它左邊
if (isBadVersion(tmp)) {
tail = tmp;
}
else {
head = tmp + 1;
}
tmp = (head+tail)/2;
}
return head;
}
}