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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,866評論 0 10
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,170評論 0 23
  • 時常會覺得自己突然會以某種方式死亡。我不知道自己的擔(dān)心從何而來,手指的顫抖或是肚子的不舒服。每天都感覺精神狀態(tài)...
    藺木木閱讀 275評論 0 0
  • 我發(fā)現(xiàn)這一個月都很忙,下一個月會更忙。有沒有發(fā)現(xiàn)我們的培訓(xùn)體系很完善,不管是公司的還是團(tuán)隊的。各種各樣的培訓(xùn)!活動...
    付愛寶二妞閱讀 357評論 0 0
  • 這世界上一定有一類女孩子, 錢自己掙,口紅自己買,搬家自己搬,生病自己去醫(yī)院,獨(dú)立的讓人有點(diǎn)心疼。 她看似能處理好...
    宛記閱讀 938評論 3 9

友情鏈接更多精彩內(nèi)容