/* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */publicclassSolutionextendsVersionControl {publicintfirstBadVersion(int n) {int left =1;int right = n;while (left < right) {// 求中点int mid = left + (right - left) /2;// 判断是不是错误版本if (isBadVersion(mid)) {// 如果是错误版本,说明其他的错误版本都在左边 right = mid; } else {// 如果不是错误版本,说明错误版本一定在之后才出现,也就是右边 left = mid +1; } }// 返回 right 也一样return left; }}
3.2 Kotlin
/* The isBadVersion API is defined in the parent class VersionControl. def isBadVersion(version: Int): Boolean = {} */classSolution: VersionControl() {overridefunfirstBadVersion(n: Int) : Int {var left =1var right = nwhile (left < right) {// 求中点val mid = left + (right - left) /2// 判断是不是错误版本if (isBadVersion(mid)) {// 如果是错误版本,说明其他的错误版本都在左边 right = mid } else {// 如果不是错误版本,说明错误版本一定在之后才出现,也就是右边 left = mid +1 } }// 返回 right 也一样return left }}