LeetCode OJ: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.

这个是简单的二分法,但是二分法的细节还是要注意一下。相当于从00000...11111中选出第一个1的。二分法的关键就是应该确保要找的值一定应该咋迭代的那个区间之中,比如这里的mid=1的时候,取end = mid, mid = 0的时候,start = mid + 1; 这样可以保证第一个1时钟在这个区间之中,追后可以得到第一个1.

还有个细节就是mid不适合用(start + end)/2,这样有可能导致溢出的情况。

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

 二分法的简单变种而已,java版本代码如下所示:

 1 public class Solution extends VersionControl {
 2     public int firstBadVersion(int n) {
 3         int beg = 1;
 4         int end = n;
 5         while (beg <= end) {
 6               int mid = beg+(end-beg)/2;
 7               if(isBadVersion(mid)){
 8                   end = mid - 1;
 9               }else{
10                   beg = mid + 1;
11               }
12         }
13         return beg; //注意边界条件,为什么返回的是beg,因为beg加上1的时候判断正好不是坏的版本,加上变成第一个,end达不到这个效果
14     }
15 }

 

posted @ 2015-10-12 18:55  eversliver  阅读(208)  评论(0编辑  收藏  举报