First Bad Version - LeetCode
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n
versions [1, 2, ..., n]
and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version)
which will return whether version
is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
思路:二分查找。
要注意的一点是,在计算中间点 mid的值时,如果用mid = (left + right) >> 1有可能结果会溢出。
这里用 mid = (left >> 1) + (right >> 1)
式子中后面如果不加括号有可能会出错,因为会把right的值当成前面left的位移操作的距离。
1 // Forward declaration of isBadVersion API. 2 bool isBadVersion(int version); 3 4 class Solution { 5 public: 6 int firstBadVersion(int n) { 7 if (n < 2) return n; 8 int left = 1, right = n; 9 while ( left < right) 10 { 11 int mid = (left >> 1) + (right >> 1); 12 bool bad = isBadVersion(mid); 13 if (bad) 14 { 15 if (mid == 1 || !isBadVersion(mid - 1)) 16 return mid; 17 right = mid; 18 } 19 else 20 { 21 if (isBadVersion(mid + 1)) 22 return mid + 1; 23 left = mid + 1; 24 } 25 } 26 return 0; 27 } 28 };