LeetCode-Solutions-in-Cpp17

Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.


Project maintained by downdemo Hosted on GitHub Pages — Theme by mattgraham
// 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;
  }
};
// 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;
  }
};