278. 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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

 

一个坏的数,后面的数也都是坏的

找出第一个坏的数

 

C++(2ms):

 1 // Forward declaration of isBadVersion API.
 2 bool isBadVersion(int version);
 3 
 4 class Solution {
 5 public:
 6     int firstBadVersion(int n) {
 7         int left = 1 ;
 8         int right  = n ;
 9         while(left < right){
10             int mid = left + (right - left)/2 ;
11             if (!isBadVersion(mid))
12                 left = mid + 1 ;
13             else
14                 right = mid ;
15         }
16         return left ;
17     }
18 };

 

posted @ 2018-01-18 09:57  __Meng  阅读(114)  评论(0编辑  收藏  举报