Leetcode 278. First Bad Version

Lintcode 74. 第一个错误的代码版本

Posted by Olivia Liu on May 1, 2020 | 阅读:

Description

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.

代码库的版本号是从 1 到 n 的整数。某一天,有人提交了错误版本的代码,因此造成自身及之后版本的代码在单元测试中均出错。请找出第一个错误的版本号。

你可以通过 isBadVersion 的接口来判断版本号 version 是否在单元测试中出错,具体接口详情和调用方法请见代码的注释部分。

Examples

Given n = 5, and version = 4 is the first bad version.

call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true

Then 4 is the first bad version. 

Answer

It is easy to come up with an O(n) solution, but it cannot pass time limit. To optimize time complexity, we can use binary search.

Time Complexity

O(logn)

Code

C++

class Solution {
public:
    int firstBadVersion(int n) {
        int lower = 1, upper = n, mid;
        while(lower < upper) 
        {
            mid = lower + (upper - lower) / 2;
            if(!isBadVersion(mid)) 
                lower = mid + 1;   /* Only one call to API */
            else upper = mid;
        }
        return lower;
    } 
};