First Bad Version
class Solution {
/**
* @param n: An integers.
* @return: An integer which is the first bad version.
*/
public int findFirstBadVersion(int n) {
int start = 1, end = n;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (SVNRepo.isBadVersion(mid)) {
end = mid;
} else {
start = mid;
}
}
if (SVNRepo.isBadVersion(start)) {
return start;
}
return end;
}
}
class Solution(object):
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
l,r = 0, n
while l <=r:
m = (l+r)//2
# we find the target:
if isBadVersion(m-1) == False and isBadVersion(m)== True:
return m
# we didn't find the target, we eleminate the half that the target cannot lie
else:
if isBadVersion(m) == False:
l = m +1
else:
r = m -1
return -1
var solution = function(isBadVersion) {
/**
* @param {integer} n Total versions
* @return {integer} The first bad version
*/
return function(n) {
let left = 1;
let right = n;
let mid;
while (left + 1 < right) {
mid = (left + right) / 2 >>> 0;
if (isBadVersion(mid)) {
right = mid;
} else {
left = mid;
}
}
return isBadVersion(left) ? left : right;
};
};
最后更新于
这有帮助吗?