依然二分,转向条件,容易出问题的地方。
对于<=情况,截止区间是0;使用mid-1需要多进行一次查找通过left=mid+1修正区间;
对于<情况,截止区间是1;使用right=mid可以直接得到正确区间。
https://leetcode.com/problems/first-bad-version/
// Forward declaration of isBadVersion API. bool isBadVersion(int version); class Solution { public: int firstBadVersion(int n) { int left = 1; int right = n; int mid ; while(left <= right) { mid = left + (right - left) / 2; if(isBadVersion(mid)) { right = mid - 1; } else { left = mid + 1; } } return left; } };
// Forward declaration of isBadVersion API. bool isBadVersion(int version); class Solution { public: int firstBadVersion(int n) { int left = 1; int right = n; int mid ; while(left < right) { mid = left + (right - left) / 2; if(isBadVersion(mid)) { right = mid; } else { left = mid + 1; } } return left; } };