LeetCode 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 returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

idea:
although this problem description is long but it’s easy to understand.
than means we need to find the first element that isBadVersion() returns true.

we can use binary search to solve problems like this.

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        //find the first bad version, which means binary search and we want to find the first one that meets our conditions
        int left = 1;
        int right = n; //tight bound
        while (left <= right) { //如果存在等于 那么right和left必然要mid-1和mid+1否则会死循环
            int mid = (right - left) / 2 + left;
            if (isBadVersion(mid)) { //if it is true
                right = mid - 1;
            } else { //if it is false
                left = mid + 1;
            }
        }
        return left; //这里return right+1或者left都是可以的 因为最后两者停止的位置肯定是right left, right肯定不是true因为之前是true然后mid-1直接不是了,所以right最后对标的肯定是最后一个false
    }
}
posted @ 2020-11-10 09:29  EvanMeetTheWorld  阅读(13)  评论(0)    收藏  举报