// The API isBadVersion is defined for you. // bool isBadVersion(int version);
classSolution { public: intfirstBadVersion(int n){ int ans = 0; int l = 1; int r = n; int mid; while(l <= r){ mid = l + (r - l) / 2; if(isBadVersion(mid)){ ans = mid; r = mid - 1; } else l = mid + 1; } return ans; } };
官方题解:
用了另一种二分模板
classSolution { public: intfirstBadVersion(int n){ int left = 1, right = n; while (left < right) { // 循环直至区间左右端点相同 int mid = left + (right - left) / 2; // 防止计算时溢出 if (isBadVersion(mid)) { right = mid; // 答案在区间 [left, mid] 中 } else { left = mid + 1; // 答案在区间 [mid+1, right] 中 } } // 此时有 left == right,区间缩为一个点,即为答案 return left; } };
classSolution { public: inthIndex(vector<int>& citations){ int l = 0; int n = citations.size(); int r = n - 1; int mid; while(l <= r){ mid = l + (r - l) / 2; if(n - mid > citations[mid]) l = mid + 1; if(n - mid <= citations[mid]) r = mid - 1; } return n - l; } };
复杂度分析
时间复杂度:O(logn),其中 n 为数组 citations 的长度。二分查找的时间复杂度为 O(logn)。