Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int l = 1;
int r = n + 1;
while (l < r) {
int m = l + (r - l) / 2;
if (isBadVersion(m)) {
r = m;
} else {
l = m + 1;
}
}
return l;
}
};
n + 1
为右边界时,若 n
为 INT_MAX
将导致越界,因此要做一些特殊处理// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int l = 1;
int r = n;
while (l <= r) { // 与第一种做法边界检查等价但不会溢出
int m = l + (r - l) / 2;
if (isBadVersion(m)) {
r = m - 1; // r 是右边界前一个位置,要少 1
} else {
l = m + 1;
}
}
return l;
}
};