278. First Bad Version

Problem

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.

Example

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. 

Code

// Forward declaration of isBadVersion API.

static int var = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
bool isBadVersion(int version);

class Solution {
public:
    int firstBadVersion(int n) {
        if(isBadVersion(1))
            return 1;
        return getBadVersion(1,(long long int)n);
    }
    int getBadVersion(long long int start,long long int end){
        if((end-start)==1)
            return end;
        long long int mid = (start+end)/2;
        if(isBadVersion(mid)){
            return getBadVersion(start,mid);
        }
        else{
            return getBadVersion(mid,end);
        }
    }
};

Result

278.First Bad Version.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,151评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,457评论 0 23
  • 时常会觉得自己突然会以某种方式死亡。我不知道自己的担心从何而来,手指的颤抖或是肚子的不舒服。每天都感觉精神状态...
    蔺木木阅读 1,553评论 0 0
  • 我发现这一个月都很忙,下一个月会更忙。有没有发现我们的培训体系很完善,不管是公司的还是团队的。各种各样的培训!活动...
    付爱宝二妞阅读 1,826评论 0 0
  • 这世界上一定有一类女孩子, 钱自己挣,口红自己买,搬家自己搬,生病自己去医院,独立的让人有点心疼。 她看似能处理好...
    宛记阅读 4,342评论 3 9