publicclassSolutionextendsVersionControl{ publicintfirstBadVersion(int n){ long begin = 1; long end = n; while(begin<end){ int mid = (int)((begin+end)>>1); if(isBadVersion(mid)&&end!=begin){ end = mid; }else{ begin = mid+1; } } return (long)begin; } }
时间复杂度
空间复杂度
O(logn)
O(1)
官方的题解提供了一种更好的方法防止溢出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution{ public: intfirstBadVersion(int n){ int left = 1, right = n; while (left < right) { int mid = left + (right - left) / 2; if (isBadVersion(mid)) { right = mid; } else { left = mid + 1; } } return left; } };