278.First Bad Versionノート

1550 ワード

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からn個のversionsがあると仮定し,1つのx以降はすべてbad versionであり,最初のbad versionを見つけ,bool isBadVersion(version)という関数をできるだけ少なく呼び出すことを要求する.半値で検索します.1つのleft初期値は1であり、1つのright初期値はnであり、1つのmidは(left+right)/2である.midがbad versionかどうかを判断します.もしそうなら、ターゲットはleft-mid区間にあります.そうでなければ、ターゲットはmid+1-right区間にあります(midはbad versionではないので、責任は最初のbad versionではないに違いありませんので、ここではmid+1から探します).もう一つ、特に大きな数に出会って、left+rightはintの範囲を超えて、このいくつかの数をlongに変えて過ぎました.コードは次のとおりです.
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);

class Solution {
public:
    int firstBadVersion(int n) {
        long left = 1;
        long right = n;
        long mid = (left+right)>>1;
        while(right!=left)
        {
            if(isBadVersion(mid))//    //   
            {
                right = mid;
                
            }
            else left = mid+1;
            mid = (left + right)>>1;
        }
        return mid;
    }
};