LeetCode 278. First Bad Version

278. First Bad Version

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.

题意:查找第一个破损的产品。
二分查找,注意两个地方:

  • mid值计算的时候,由于两个数太大,使用另外一种计算方法

  • 用ans来记录符合情况的值,然后 l ,r 分别加减1,判断条件为l<=r,避免死循环

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

class Solution {
public:
    int firstBadVersion(int n) {
        int l = 1, r = n, ans = 0;
        while(l <= r)
        {
            int mid = (r-l)/2 + l;
            if(isBadVersion(mid)) ans = mid,r = mid - 1;
            else l = mid + 1;
        }
        return ans;
    }
};

你可能感兴趣的:(leetcode,*LeetCode)