278.First Bad Version
278.First Bad Version
难度:Easy
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.
1
Example:
2
3
Given n = 5, and version = 4 is the first bad version.
4
5
call isBadVersion(3) -> false
6
call isBadVersion(5) -> true
7
call isBadVersion(4) -> true
8
9
Then 4 is the first bad version.
Copied!
二分法?
1
// Forward declaration of isBadVersion API.
2
bool isBadVersion(int version);
3
4
class Solution {
5
int firstBadVersion(int left, int right) {
6
if(left +1== right) return isBadVersion(left) ?left:right;
7
int mid=left+(right-left)/2 ;
8
// cout<<mid<<endl;
9
return isBadVersion(mid)? firstBadVersion(left,mid) : firstBadVersion(mid,right);
10
}
11
public:
12
int firstBadVersion(int n) {
13
if(n==1) return 1;
14
return firstBadVersion(1,n);
15
16
}
17
};
Copied!
执行用时 :4 ms, 在所有 C++ 提交中击败了73.59%的用户 内存消耗 :8.2 MB, 在所有 C++ 提交中击败了31.63%的用户
Copy link