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

思路:

1、采用二分查找法找到当前版本为坏版本,但是前一版本为好版本;

2、注意边界情况的处理,特别是头尾;

3、如果没有找到,返回-1;

代码:

// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
class Solution {
public:
    int firstBadVersion(int n) {
    if(n < 1)
    {
        return -1;
    }
    int low = 1;
    int high = n;
    int mid;
    while(low + 1 < high)
    {
        mid = low + (high - low) / 2;
        if(isBadVersion(mid))
        {
            high = mid; // 从前半段开始找
        }
        else 
             {
                 low = mid;   //从后半段开始找
             }
    }
        if (isBadVersion(low))    
        {
            return low;
        } 
        else if (isBadVersion(high)) 
        {
            return high;
        }
    return -1;
    }
};



你可能感兴趣的:(LeetCode,C++)