今日简单题:https://leetcode-cn.com/problems/first-bad-version/
比较清晰的二分法,关注下while不要死循环即可。
另外吐槽一下题解,mid=head+(tail-head)/2; 那不就是mid=(head+tail)/2吗?这个还更直观,就是中位数。
贴下代码:
/* 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是坏版本,那第一个坏版本一定在它左边
if (isBadVersion(tmp)) {
tail = tmp;
}
else {
head = tmp + 1;
}
tmp = (head+tail)/2;
}
return head;
}
}
网友评论