First Bad Version

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.

 

Analyse: find a number k in an continuous set {1, 2, ..., n}. Binary search.

Runtime: 0ms.

 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 == 0) return 0;
 8         if(n == 1) return isBadVersion(1);
 9         
10         long long low = 0, high = n;
11         while(low < high){
12             long long mid = (low + high) >> 1;
13             if(isBadVersion(mid)) high = mid;
14             else low = mid + 1;
15         }
16         return high;
17     }
18 };

 

posted @ 2015-09-10 05:02  amazingzoe  阅读(93)  评论(0编辑  收藏  举报