LeetCode[7] - First Bad Version

這個挺直接的,也被李特標了EASY.
就是在1~n里面找第一個出錯點。其實就是搜一個數(shù)字i(同時用isBadVersion(i))檢查這個數(shù)字是否報錯。那搜index的活,直接binary search就好了。
注意特別條件:

!isBadVersion(i) && isBadVersion(i+1)

一定要找出這個i+1,就是第一個出錯點。

還有就是:很可能start == end了呀,如果還沒有完結(jié),那么最終的那個情況必然是start==end==mid, 然后既然mid之前沒找到錯,那么try 一try isBadVersion(mid) 就好了。

/*
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.
*/

/* The isBadVersion API is defined in the parent class VersionControl.
      boolean isBadVersion(int version); */

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        if (n <= 1) {
            return isBadVersion(n) ? n : -1;
        }
        int start = 1;
        int end = n;
        int mid = start + (end - start) / 2;
        while(start < end) {
            mid = start + (end - start) / 2;
            if (!isBadVersion(mid) && isBadVersion(mid + 1)) {
                return mid + 1;
            } else if (!isBadVersion(mid)){
                start = mid;
            } else {
                end = mid;
            }
        }
        return isBadVersion(mid) ?  mid : -1;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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