其他分享
首页 > 其他分享> > 【leetcode】278. First Bad Version

【leetcode】278. First Bad Version

作者:互联网

problem

278. First Bad Version

solution1:遍历;

// Forward declaration of isBadVersion API.
bool isBadVersion(int version);

class Solution {
public:
    int firstBadVersion(int n) {
        int ver = 1;
        while(ver<n)
        {
            if(isBadVersion(ver)) return ver;
            ver++;
        }
        return ver;
    }
};

solution2:二分法;

// Forward declaration of isBadVersion API.
bool isBadVersion(int version);

class Solution {
public:
    int firstBadVersion(int n) {
        int left = 1, right = n, mid;
        while(left<right)
        {
            mid = left + (right-left)/2;
            if(isBadVersion(mid)) right = mid;
            else left = mid + 1;//err.
        }
        return left;
    }
};

 

 

参考

1. Leetcode_278_First Bad Version;

 

标签:int,isBadVersion,Bad,Version,278,First
来源: https://www.cnblogs.com/happyamyhope/p/10403202.html