278. First Bad Version

278. First Bad Version

My Submissions
Question
Total Accepted: 33285  Total Submissions: 152183  Difficulty: 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.

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

Subscribe to see which companies asked this question

Hide Tags
  Binary Search
Hide Similar Problems
  (M) Search for a Range (M) Search Insert Position

分析:

典型的二分搜索问题,注意截止条件即可!

时间复杂度:O(lg(n))

空间复杂度:O(1)

// Forward declaration of isBadVersion API.
bool isBadVersion(int version);

class Solution {
public:
    int firstBadVersion(int n) {
        int low=1,high=n;
        while(low<=high)
        {
            int mid=low+(high-low)/2;//测试案例有超大数,这样写更安全
            if(isBadVersion(mid))//如果是坏的版本
                high=mid-1; //则一定在包括mid的左边(代码写成没有包括mid,所以low=high继续误差判断一次即可)
            else//如果是好的,则一定在mid的右边
                low=mid+1;
        }
        return low;
    }
};


这样跌或许二分意义更加明确:

// Forward declaration of isBadVersion API.
bool isBadVersion(int version);

class Solution {
public:
    int firstBadVersion(int n) {
        int low=1, high=n;  
        while(low<high) {  
            int mid=low + (high-low)/2;  
            if(isBadVersion(mid))  
                high = mid;  //则一定在包括mid的左边(代码写成包括mid,所以low=high不用继续判断了)
            else  
                low = mid + 1;  //则一定在不包括mid的右边
        }  
        return low; 
    }
};


联动上一个问题:<LeetCode OJ> 35. Search Insert Position

针对典型的二分搜索写法,low和high中的有一个必须进行跨步移动(即必须在mid的基础上+1或者-1),否则死循环。如果跨步移动不符合实际的意义,截止条件再进行一次误差判断即可!



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50735869

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

你可能感兴趣的:(LeetCode,C++,算法,面试,二分法)